如何使用springboot安全性创建注销

yc0p9oo0  于 2022-10-30  发布在  Spring
关注(0)|答案(3)|浏览(145)

这是我的登录名。我将使用path("/logout")实现一个logout方法,以便当前的用户会话真正注销。我使用的是Spring Security

@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response login(User credentials) {

    if(credentials == null){
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    try {
        User userInfo = new User();
        UserDetails userDetails = userDetailsService.loadUserByUsername(credentials.getUsername

        // Create authRequest Object with User ind DB, Credentials from Web-client
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userDetails, credentials.getPassword(), userDetails.getAuthorities());

        // Authenticate the user
        Authentication authentication = authenticationManager.authenticate(authRequest);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);

        userInfo.setUsername(authentication.getName());

        return Response.status(Response.Status.OK).entity("Login succesfull").build();
    }
    catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        return Response.status(Response.Status.UNAUTHORIZED).entity("Login failed").build();
    }
}
mctunoxg

mctunoxg1#

@GetMapping("/logout")
    public String getLogoutPage(HttpServletRequest request, HttpServletResponse response){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            new SecurityContextLogoutHandler().logout(request, response, authentication);

        return "redirect:/login";
    }
yhxst69z

yhxst69z2#

不使用Web安全配置器适配器:

@Configuration
@AllArgsConstructor
public class SecurityConfig {

    private final CustomAuthenticationProvider authenticationProvider;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .csrf().disable()
                .logout()
                .logoutUrl("/logout")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .and()
                .build();
    }
}
yacmzcpb

yacmzcpb3#

另一个解决方案是使用Spring安全适配器。
检查文档:https://docs.spring.io/spring-security/site/docs/4.2.4.BUILD-SNAPSHOT/reference/htmlsingle/#jc-logout

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http               
                .logout().logoutUrl("/logout.html");

    }
}

相关问题