Spring boot basic authentication

后端 未结 3 1971
一整个雨季
一整个雨季 2020-12-18 13:13

I\'m using spring boot security to help me to make authentication...


    org.springframework.boot
    

        
3条回答
  •  我在风中等你
    2020-12-18 14:00

    You need to permit access to the login endpoint (at least). E.g.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login", "/error").permitAll()
                .antMatchers("/**").authenticated().and().exceptionHandling()
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
    }
    

    If I were you I would remove the @EnableWebSecurity (and let Spring Boot do it's job) as well. And then in the login endpoint you need to set the security context, e.g.

    @PostMapping
    public void authenticate(@RequestParam Map map,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        Authentication result = authService.authenticate(map.get("username"), map.get("password"));
        SecurityContextHolder.getContext().setAuthentication(result);
        handler.onAuthenticationSuccess(request, response, result);
    }
    

    The authService should throw BadCredentialsException if the user cannot be authenticated. Here's a sample app that I used in a blog once: https://github.com/dsyer/mustache-sample/blob/7be8459173d0b65b6d44d05f86e581d358ea9b2e/src/main/java/com/example/DemoApplication.java#L177

提交回复
热议问题