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

时间:2017-09-23 08:39:00

标签: java spring spring-mvc spring-boot spring-security

这是我的登录信息。我将使用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();
    }
}

2 个答案:

答案 0 :(得分:0)

@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";
    }

答案 1 :(得分:0)

另一种解决方案是使用弹簧安全适配器。

查看文档:{​​{3}}

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {



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

    }
}