久久久久久久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.

我已經(jīng)編寫了模型、數(shù)據(jù)庫請求的存儲庫.現(xiàn)在我已經(jīng)集成了 Security 和 jwt 令牌.

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

現(xiàn)在我需要離散化用戶的角色,因為用戶無法調(diào)用需要管理員權(quán)限的路由.

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 令牌中,在令牌驗證后提取它們并作為主體的權(quán)限"傳遞:

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);

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

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

相關(guān)文檔推薦

How to wrap text around components in a JTextPane?(如何在 JTextPane 中的組件周圍環(huán)繞文本?)
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 數(shù)據(jù)庫)
Why does Spring-data-jdbc not save my Car object?(為什么 Spring-data-jdbc 不保存我的 Car 對象?)
Use threading to process file chunk by chunk(使用線程逐塊處理文件)
主站蜘蛛池模板: 日韩高清中文字幕 | 亚州精品成人 | 精品中文字幕在线观看 | 国产精品日韩欧美一区二区三区 | 国产成人精品一区二区三区在线 | 蜜月aⅴ免费一区二区三区 99re在线视频 | 国产精品久久久久久久久久三级 | 亚洲日产精品 | 一级做a爰片久久毛片 | 精品久久网 | 午夜欧美一区二区三区在线播放 | 在线观看国产wwwa级羞羞视频 | 黄色永久免费 | 国产精品一区二区三区在线播放 | 国产精品伦理一区二区三区 | 色偷偷噜噜噜亚洲男人 | 国产91久久久久蜜臀青青天草二 | 久久久久亚洲精品 | 91视频网 | 乱一性一乱一交一视频a∨ 色爱av | 成人av观看| 欧美成人a∨高清免费观看 老司机午夜性大片 | av在线一区二区三区 | 午夜免费精品视频 | 日本免费视频在线观看 | 国产精品夜间视频香蕉 | 精品综合在线 | 天天干免费视频 | 免费在线观看h片 | 99亚洲精品| 伊人精品久久久久77777 | 一级欧美 | 北条麻妃一区二区三区在线观看 | 青青久久久 | 成人欧美一区二区三区黑人孕妇 | 日韩一区二区三区在线 | 婷婷综合网| 羞羞视频在线观免费观看 | 亚洲综合一区二区三区 | 91高清在线观看 | 激情一区|