Spring Security CustomUserDetails无效,SecurityContextHolder.getContext()。getAuthentication()。getPrincipal()只返回用户名

时间:2017-05-17 15:06:08

标签: java spring spring-security spring-security-oauth2

我是spring-security和spring-security-oauth2的新手,使用springboot。

我想要一些额外的属性,所以我自定义了UserDetails和UserDetailsS​​ervice。

public class CustomUserDetails implements UserDetails {

    private User user;
    private Long id;

    public CustomUserDetails(User user) {
        this.user = user;
        this.id = user.getId();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getMobile();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {

        // my model User
        User user = userMapper.selectByPhone(phone);

        if (user == null) {
            throw new UsernameNotFoundException("");
        }

        return new CustomUserDetails(user);

    }
}

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    private UserDetailsService userDetailsService;

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

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
            .anonymous().disable()
            .authorizeRequests()
            .antMatchers("/oauth/token").permitAll()
            .anyRequest().authenticated();
    }

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

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Autowired
    private DataSource dataSource;

    @Autowired
    @Qualifier("customUserDetailsService")
    private UserDetailsService userDetailsService;

    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .jdbc(dataSource);
    }

    public DefaultTokenServices tokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        defaultTokenServices.setAccessTokenValiditySeconds(100);
        defaultTokenServices.setRefreshTokenValiditySeconds(10000);
        return defaultTokenServices;
    }

    @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            .tokenStore(tokenStore())
            .tokenServices(tokenServices())
            .userDetailsService(userDetailsService)
            .authenticationManager(authenticationManager);
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }
}

我想调用SecurityContextHolder.getContext().getAuthentication().getPrincipal()返回CustomUserDetails而不是String。我尝试了我在互联网上找到的所有内容,但没有任何工作。

1 个答案:

答案 0 :(得分:-1)

您可以使用以下会话范围创建一个bean(spring组件):

import com.tk.graph.app.model.MyUser;
import com.tk.graph.app.repository.MyUserRepository;

@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class LoggedUserBean {

    @Autowired
    private MyUserRepository MyUserDao;

    private MyUser MyUser;

    public MyUser getMyUser() {
        if(MyUser==null){
            System.out.println("Etait null ");
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();   
            MyUser  = MyUserDao.findByLogin(auth.getName()).get(0);
        }
        return MyUser;
    }

    public void setMyUser(MyUser MyUser) {
        this.MyUser = MyUser;
    }
}

你可以使用@Autowired注释在任何spring composent中调用它。