为什么我在jwt的春季靴上被禁止

时间:2018-08-12 11:30:00

标签: spring-boot spring-security authorization jwt

我设置了2个用户角色和终结点所在的UserController。我在认证JWTAuthectionFilter,JwtAuthetorizationFilter时进行过滤。根据这些角色,端点具有访问权限。但是,尽管角色是正确的,但为什么我还是被禁止使用。请帮助我

我在UserController.java上的端点

@ApiOperation(value = "Return All Users")
@ApiResponses(value = {
        @ApiResponse(code = 403, message = "Forbidden. You have to take a token from /login path") })
@PreAuthorize("hasRole('SELLER')")
@GetMapping
public List<User> getAllUser() {
    List<User> users = this.userRepository.findAll();
    return users;
}

ApplicationSecurity.java上的WebSecurity配置器

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().authorizeRequests().antMatchers(SIGN_UP_URL).permitAll()
            .antMatchers(SIGN_IN_URL).permitAll()
            .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security",
                    "/swagger-ui.html", "/webjars/**", "/swagger.json")
            .permitAll().anyRequest().authenticated().and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager()))
            // this disables session creation on Spring Security
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

JWTAuthenticationFilter.java

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

private AuthenticationManager authenticationManager;

public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
    this.authenticationManager = authenticationManager;
}

@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
        throws AuthenticationException {

    try {

        User creds = new ObjectMapper().readValue(req.getInputStream(), User.class);

        return authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword()));

    } catch (IOException e) {
        throw new RuntimeException();

    }
}

@Override
public void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
        Authentication auth) throws IOException, ServletException {
    String authorities = auth.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority)
            .collect(Collectors.joining(","));
    System.out.println(authorities);
    String token = JWT.create()
            .withSubject(((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername())
            .withClaim("ROLE", authorities)
            .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME)).sign(HMAC512(SECRET.getBytes()));
    // token added the header
    res.addHeader(HEADER_STRING, TOKEN_PREFIX + token);

}}

JWTAuthorizationFilter.java

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

public JWTAuthorizationFilter(AuthenticationManager authManager) {
    super(authManager);
}

@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    String header = req.getHeader(HEADER_STRING);

    if (header == null || !header.startsWith(TOKEN_PREFIX)) {
        chain.doFilter(req, res);
        return;
    }

    UsernamePasswordAuthenticationToken authentication = getAuthentication(req);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    chain.doFilter(req, res);

}

private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
    String token = request.getHeader(HEADER_STRING);
    if (token != null) {
        // parse the token.
        String user = JWT.require(Algorithm.HMAC512(SECRET.getBytes())).build()
                .verify(token.replace(TOKEN_PREFIX, "")).getSubject();

        String role = JWT.require(Algorithm.HMAC512(SECRET.getBytes())).build()
                .verify(token.replace(TOKEN_PREFIX, "")).getClaim("ROLE").toString();



        if (user != null) {
            return new UsernamePasswordAuthenticationToken(user, null, Arrays.asList(new SimpleGrantedAuthority(role)));
        }
        return null;
    }
    return null;
}}

UserDetailsS​​erviceImpl.java

public class UserDetailsServiceImpl implements UserDetailsService {
private UserRepository userRepository;

public UserDetailsServiceImpl(UserRepository userRepository) {
    this.userRepository = userRepository;
}

@Override
public UserDetails loadUserByUsername(String username) {
    User user = userRepository.findByUsername(username);
    List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
    if (user != null) {
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
                authorities);
    } else {
        throw new UsernameNotFoundException(username);
    }

}

private List<GrantedAuthority> getUserAuthority(Set<Role> userRoles) {
    Set<GrantedAuthority> roles = new HashSet<>();
    userRoles.forEach((role) -> {
        roles.add(new SimpleGrantedAuthority(role.getRole()));
    });

    List<GrantedAuthority> grantedAuthorities = new ArrayList<>(roles);
    return grantedAuthorities;
}}

0 个答案:

没有答案