Spring安全上下文在休息/肥皂呼叫中是否持久存在?

时间:2019-06-17 09:20:08

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

从客户端调用rest / soap服务时,Spring安全上下文是否持久存在。我有一个客户端应用程序,它使用SecurityContextHolder.getContext()。setAuthentication()设置身份验证。客户端应用程序在需要获取上下文的地方进行休息/肥皂调用。

//Setting security context in client application: 
User contextUser = new User(username, enc_password, true, true, true, true,grantedAuthorities, null);
authentication = new UsernamePasswordAuthenticationToken(contextUser, username,grantedAuthorities);
SecurityContextHolder.getContext().setAuthentication(authentication);

// on server side 
// I want to get following authentication on server side to get logged in user
Authentication auth=SecurityContextHolder.getContext().getAuthentication();

    User user= null;
    if (auth != null && !(auth instanceof AnonymousAuthenticationToken)) {
        // userDetails = auth.getPrincipal()

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        String username = null;
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
            user = (UserDetails) principal;

        } else {
            username = principal.toString();
        }       
    }

1 个答案:

答案 0 :(得分:0)

要在服务器端访问username,请在进行REST / SOAP API调用后,通过在调用API之前在每个请求的标头中添加用户名来实现。

使用Spring Interceptor拦截服务器端的每个请求,您可以通过实现HandlerInterceptorAdapter接口来创建拦截器类。

For more information about interceptors.