久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

Spring Boot 如何使用 jwt 管理用戶角色

Spring boot how make a user role managing with jwt(Spring Boot 如何使用 jwt 管理用戶角色)
本文介紹了Spring Boot 如何使用 jwt 管理用戶角色的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在用 spring boot 編寫一個 RESTful api.我正在使用 spring boot、jersey、mongo db、swagger、spring boot security 和 jwt.

I'm writing a RESTful api with spring boot. I'm using spring boot, jersey, mongo db, swagger, spring boot security and jwt.

我已經編寫了模型、數據庫請求的存儲庫.現在我已經集成了 Security 和 jwt 令牌.

I have written the models, the repositories for the requests to the DB. Now I have integrated the Security and jwt token.

現在我需要離散化用戶的角色,因為用戶無法調用需要管理員權限的路由.

Now I need to discretize the role of the users, because a user cant call a route that need an admin priviledges.

我有一個登錄路徑,它返回一個令牌.這是我的 SecurityConfig 的代碼

I have a route for login, it's return a token. This is the code of my SecurityConfig

...
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserRepository userRepository;

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/api/swagger.json").permitAll()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .antMatchers("/api/*").authenticated()
                .and()

                .addFilterBefore(new JWTLoginFilter("/login", authenticationManager(), userRepository),
                        UsernamePasswordAuthenticationFilter.class)

                .addFilterBefore(new JWTAuthenticationFilter(),
                        UsernamePasswordAuthenticationFilter.class);
    }

}

我編寫了 JWTLoginFilter,當用戶登錄時返回我的令牌

I written the JWTLoginFilter that return me the token when user makes login

...
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException {
    Credential creds = new ObjectMapper().readValue(req.getInputStream(), Credential.class);

    User user = userRepository.login(creds);

    if (user == null)
        throw new BadCredentialsException("");

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
        creds.getUsername(),
        creds.getPassword()
    );

    return token;
}
...

我想在方法的端點類中插入它

I want insert this on my endpoint class on method

@PreAuthorize("hasRole('ROLE_ADMIN')")

這是端點的一部分

....

@Component
@Path("story")
@Api(value = "Story", produces = "application/json")
public class StoryEndpoint {

    private static final Logger LOGGER = LoggerFactory.getLogger(StoryEndpoint.class);

    @Autowired
    StoryRepository storyRepository;


    @GET
    @Path("/")
    @Produces(MediaType.APPLICATION_JSON)
    @PreAuthorize("hasRole('ROLE_ADMIN')") <--- I want insert here
    @ApiOperation(value = "Get All Story", response = Story.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "hello resource found"),
            @ApiResponse(code = 404, message = "Given admin user not found")
    })
    public Response getAllStory(){
        Iterable<Story> stories = storyRepository.findAll();
        LOGGER.info("getAllStory");
        return (stories!=null) ? Response.ok(stories).build() : Response.ok(ResponseErrorGenerator.generate(Response.Status.NOT_FOUND)).status(Response.Status.NOT_FOUND).build();
    }
....

如何制定一種機制來為用戶分配角色,以及如何在令牌中傳遞角色并離散化路由用戶角色?

How I can make a mechanism for assign to user the role and how i can pass the role in token and discretize on route the role of user?

推薦答案

您需要將用戶角色作為附加聲明存儲在 JWT 令牌中,在令牌驗證后提取它們并作為主體的權限"傳遞:

You need to store user roles inside JWT token as additional claims, extract them after token validation and pass as 'authorities' for principal:

 Collection<? extends GrantedAuthority> authorities
                = Arrays.asList(claims.get(AUTHORITIES_KEY).toString().split(",")).stream()
                .map(authority -> new SimpleGrantedAuthority(authority))
                .collect(Collectors.toList());

        User principal = new User(claims.getSubject(), "",
                authorities);

        UsernamePasswordAuthenticationToken t
                = new UsernamePasswordAuthenticationToken(principal, "", authorities);

這篇關于Spring Boot 如何使用 jwt 管理用戶角色的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to wrap text around components in a JTextPane?(如何在 JTextPane 中的組件周圍環繞文本?)
MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何獲取插入的自動生成密鑰?[MySql])
Inserting to Oracle Nested Table in Java(在 Java 中插入 Oracle 嵌套表)
Java: How to insert CLOB into oracle database(Java:如何將 CLOB 插入 oracle 數據庫)
Why does Spring-data-jdbc not save my Car object?(為什么 Spring-data-jdbc 不保存我的 Car 對象?)
Use threading to process file chunk by chunk(使用線程逐塊處理文件)
主站蜘蛛池模板: 一区二区三区在线 | 免费国产视频 | 一级免费毛片 | 国产日韩欧美在线观看 | 国产一级在线 | 免费的黄色片子 | 国产不卡视频在线 | 欧美久久一区二区 | 国产精品视频yy9299一区 | 午夜免费观看体验区 | 欧美5区 | 国产欧美日韩综合精品一区二区 | 成年人在线观看 | 国产日韩一区二区三免费高清 | 国产精品精品 | 中文字幕第7页 | 亚洲国产成人精品女人久久久 | 91在线看视频| 中文字幕日韩欧美一区二区三区 | 久色视频在线 | 国产日韩欧美一区二区 | 久久成人18免费网站 | 成人精品一区二区户外勾搭野战 | 久久中文字幕av | 成人在线免费网站 | 国产精品一区二区久久久久 | 国产视频在线观看一区二区三区 | 亚洲欧美日韩电影 | 国产美女永久免费无遮挡 | 精品久久99 | 精品一区二区免费视频 | 日韩在线小视频 | 国精产品一区二区三区 | 蜜臀网| 久久久精品久久 | 亚洲天堂av在线 | 欧美日韩综合视频 | 成人在线观看免费视频 | 久久精品国产一区二区三区 | 午夜看看 | 综合色影院 |