getPrincipal()方法返回用户名而不是UserDetails

时间:2019-01-20 18:44:10

标签: java spring-boot spring-security oauth-2.0

我有一个使用spring boot的项目,带有oauth2的spring security。当我使用   SecurityContextHolder.getContext()。getAuthentication()。getPrincipal()

在示例中,该方法仅返回用户名结尾,我看到此方法返回了UserDetails命令。

遵循设置

OAuthSecurityConfig.java:

package br.com.altha.api.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;

import br.com.altha.api.security.CustomUserDetailsService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
@EnableAuthorizationServer
@EnableResourceServer
@Order(SecurityProperties.BASIC_AUTH_ORDER-2)
@Import(Encoders.class)
public class OAuthSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder userPasswordEncoder;

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

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

}

AuthorizationServerConfig.java:

package br.com.altha.api.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import br.com.altha.api.security.CustomUserDetailsService;

@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private static final String SECRET = "PASSWORD";

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder oauthClientPasswordEncoder;

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").passwordEncoder(oauthClientPasswordEncoder);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("altha-adms")
            .secret(oauthClientPasswordEncoder.encode(SECRET))
            .scopes("write", "read")
            .authorizedGrantTypes("password", "refresh_token")
            .accessTokenValiditySeconds(60/*1800*/)
            .refreshTokenValiditySeconds(1800);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            .tokenStore(tokenStore())
            .accessTokenConverter(accessTokenConverter())
            .authenticationManager(authenticationManager)
            .reuseRefreshTokens(false)
            .userDetailsService(userDetailsService);
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(SECRET);
        return converter;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }
}

ResourceServerConfig.java:

package br.com.altha.api.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler;

import br.com.altha.api.handler.RestExceptionHandler;

@Configuration
@Import(Encoders.class)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Bean
    public RestExceptionHandler handlerError() {
        return new RestExceptionHandler();
    }

    @Bean
    public MethodSecurityExpressionHandler createExpressionHandler() {
        return new OAuth2MethodSecurityExpressionHandler();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/public/**").permitAll()
            .antMatchers("/private/**").authenticated()
            .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.stateless(true);
    }
}

4 个答案:

答案 0 :(得分:3)

我可以使用以下代码解决此问题:

我在UserAuthenticationConverter中添加了一个豆子

@Bean
public UserAuthenticationConverter userAuthenticationConverter() {
    DefaultUserAuthenticationConverter defaultUserAuthenticationConverter = new DefaultUserAuthenticationConverter();
    defaultUserAuthenticationConverter.setUserDetailsService(userDetailsService);
    return defaultUserAuthenticationConverter;
}

此后,我在JwtAccessTokenConverter中设置了这个bean

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    final JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
    jwtAccessTokenConverter.setSigningKey(SECRET);
    ((DefaultAccessTokenConverter) jwtAccessTokenConverter.getAccessTokenConverter())
            .setUserTokenConverter(userAuthenticationConverter());
    return jwtAccessTokenConverter;
}

答案 1 :(得分:1)

原因可能因身份验证/授权技术而异,但在我的情况下,我有2个过滤器身份验证/授权,问题是将username而不是整个用户对象传递给授权中的UsernamePasswordAuthenticationToken过滤器:

return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), .....);

第一个构造函数参数被设置为Principle对象。

因此解决方法是传递整个userDetails对象

return new UsernamePasswordAuthenticationToken(userDetails, .....);

答案 2 :(得分:0)

使用Spring Boot 1.5.x,您可以实现PrincipalExtractor并覆盖其Object extractPrincipal(Map<String, Object> map)。以下示例组件具有一个自动连接的UserdetailsS​​ervice,用于根据用户名查找UserDetails对象。

@Component
public class MyPrincipalExtractor implements PrincipalExtractor {

    private UserDetailsService userDetailsService;

    @Value("${security.oauth2.client.principal-attribute}")
    private String principalAttribute;

    @Autowired
    public MyPrincipalExtractor(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Object extractPrincipal(Map<String, Object> map) {
        if (!map.containsKey(principalAttribute)) {
            return null;
        }

        final String username = (String) map.get(principalAttribute);
        try {
            return userDetailsService.loadUserByUsername(username);
        } catch (UsernameNotFoundException e) {
            // This may be the first time this user is accessing the system, 
            // maybe you want to extract some other attributes from the map 
            // and return a different type of user object that can be used to 
            // create a new user. 
        }
    }
}

现在SecurityContextHolder.getContext().getAuthentication().getPrincipal()将包含一个UserDetails对象。

有关更详细的教程,请参见:

答案 3 :(得分:0)

对我有用。谢谢。

@Bean
public UserAuthenticationConverter userAuthenticationConverter() {
    DefaultUserAuthenticationConverter defaultUserAuthenticationConverter = new DefaultUserAuthenticationConverter();
    defaultUserAuthenticationConverter.setUserDetailsService(userDetailsService);
    return defaultUserAuthenticationConverter;
}

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    final JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
    jwtAccessTokenConverter.setSigningKey(SECRET);
    ((DefaultAccessTokenConverter) jwtAccessTokenConverter.getAccessTokenConverter())
            .setUserTokenConverter(userAuthenticationConverter());
    return jwtAccessTokenConverter;
}