【问题标题】:Spring Security CustomUserDetails not working, SecurityContextHolder.getContext().getAuthentication().getPrincipal() just return usernameSpring Security CustomUserDetails 不起作用,SecurityContextHolder.getContext().getAuthentication().getPrincipal() 只返回用户名
【发布时间】:2017-10-17 03:17:27
【问题描述】:

我是 spring-security 和 spring-security-oauth2 的新手。

我想要一些额外的属性,所以我自定义了 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 而不是字符串。我尝试了我在互联网上找到的所有方法,但没有任何效果。

【问题讨论】:

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


    【解决方案1】:

    您可以创建一个具有类似会话范围的 bean(弹簧组件):

    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中调用它。

    【讨论】:

    • 我已经从 CustomUserDetailsS​​ervice 获得了用户,我不想通过数据库获得两次,谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-07-08
    • 2014-04-07
    • 2018-01-27
    • 2017-04-25
    • 1970-01-01
    • 2016-07-24
    • 2014-06-15
    相关资源
    最近更新 更多