小编Mar*_*oli的帖子

Spring启动如何使用jwt管理用户角色

我正在用spring boot编写一个RESTful api.我正在使用春季靴子,运动衫,mongo db,swagger,spring boot security和jwt.

我已经编写了模型,请求数据库的存储库.现在我已经集成了Security和jwt令牌.

现在我需要离散用户的角色,因为用户无法调用需要管理员权限的路由.

我有一个登录路线,它返回一个令牌.这是我的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);
    }

}
Run Code Online (Sandbox Code Playgroud)

我编写了JWTLoginFilter,当用户登录时返回令牌

...
@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 …
Run Code Online (Sandbox Code Playgroud)

java roles spring-security jwt spring-boot

2
推荐指数
2
解决办法
2万
查看次数

标签 统计

java ×1

jwt ×1

roles ×1

spring-boot ×1

spring-security ×1