获得具有allowAll权限的端点的401

时间:2019-08-05 17:20:32

标签: java spring-boot spring-security

即使在antMatcher中将其定义为“ permitAll”,也要为“ / register”端点获取401。

我是Spring Security的新手。 我已经配置了两个端点“ / login”和“ / register”。我希望“ / register”可以公开使用,并且在访问“ / login”时应该进行用户名/密码检查。

我的server.servlet.context-path设置为“ / todo / user”。

我试图寻找解决方案,但是没有任何东西可以解释为什么我要面对这个问题,或者我无法理解它是新问题。

控制器类

@Controller
@RequestMapping(value = "/register")
public class RegistrationController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "", method = RequestMethod.POST,
            produces = "application/json")
    @ResponseBody
    public ResponseEntity<String> registration(@RequestBody @Valid UserRegistration userRegistration) {

        Optional<UserRegistration> user = Optional.ofNullable(userRegistration);
        if(!user.isPresent()) {
            throw new UserDataNotAvailableException("User data is not available");
        }
        //TO-DO Write implementation of isUserValid
        Optional<Boolean> isRegistrationSuccess = user.map(userService::registerNewUser);

        return new ResponseEntity<String>("This is temp", HttpStatus.OK);
    }
}

SecurityConfig

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpMethod.POST, "/register").permitAll()
                .anyRequest().authenticated()
                .and().addFilter(new 
JwtAuthenticationFilter(authenticationManager()));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }
}

身份验证过滤器

public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private static final int EXPIRATION_TIME = 3900;

    private static final String HEADER_NAME = "auth";

    private AuthenticationManager authenticationManager;

    @Value("${jwt.secret}")
    private String secret;

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

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        try{
            UserLogin user = new ObjectMapper().readValue(request.getInputStream(), UserLogin.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getEmailId(), user.getPassword(),
                    new ArrayList<>()));
        }catch (IOException e) {
            throw new InternalServerException("There was a problem in processing the request");
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                            FilterChain chain, Authentication authResult) throws IOException, ServletException {

        String jwt = Jwts.builder().setSubject(((UserLogin)authResult.getPrincipal()).getEmailId())
                .setExpiration(new Date(System.currentTimeMillis()  + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.ES256, secret)
                .compact();
        response.addHeader(HEADER_NAME, jwt);

    }
}

从安全配置类可以明显看出,我已允许所有人访问我的“ / register”端点。

但是当我在“ / register”上请求时,我得到了401。 事实并非如此,我应该能够在没有任何JWT的情况下访问该特定端点

0 个答案:

没有答案