Spring Security的authentication.getName在控制器中返回null

时间:2019-02-15 11:30:00

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

这是我在春季的第一个项目。我正在尝试获取登录用户的用户名,但它返回SELECT table1.nome, table1.id, LISTAGG(table3.nome, ', ') WITHIN GROUP (ORDER BY table3.nome) OVER (PARTITION BY table1.id) as "bairro" FROM table1 LEFT JOIN table2 on table2.escola = table1.id LEFT JOIN table3 on table3.id = table2.bairro WHERE table1.situacao = 'EM_ATIVIDADE' ORDER BY table1.id 。我还尝试了null批注和其他方法,但仍返回AuthenticationPrincipal

null类:

WebSecurityConfiguration

@EnableWebSecurity public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{ @Autowired private UserDetailsService customUserDetailsService; @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean (); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(customUserDetailsService) .passwordEncoder(encoder()); } @Override protected void configure (HttpSecurity http) throws Exception { http .csrf().disable() .antMatcher("/**") .authorizeRequests() .antMatchers("/login**").permitAll() .anyRequest().authenticated(); } public PasswordEncoder encoder() { return NoOpPasswordEncoder.getInstance(); } } 类:

AuthorizationServerConfiguration

@Configuration @EnableAuthorizationServer public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private DataSource dataSource; @Autowired private CustomUserDetailsService userDetailsService; @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager) .tokenStore(tokenStore()) .userDetailsService(userDetailsService) .approvalStoreDisabled(); } @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource); } } 类:

ResourceServerConfiguration

下面是控制器:

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter{

    @Autowired
    TokenStore tokenStore;

    @Autowired
    DataSource dataSource;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("scout").tokenStore(tokenStore);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http
            .authorizeRequests()
                .antMatchers("/oauth/token", "/oauth/authorize **").permitAll();
        http
            .requestMatchers()
                .antMatchers("/api/patients/**")
                .and()
            .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/api/patients/{\\d+}").access("hasAnyRole('PATIENT', 'DOCTOR')")
                .antMatchers("/api/patients/{\\d+}/medical-records").access("hasAnyRole ('PATIENT', 'DOCTOR')")
                .antMatchers("/api/patients/medical-records/{\\\\d+}/prescriptions").access("hasAnyRole('PATIENT', 'DOCTOR')")
                .antMatchers("/api/patients/**").access("hasRole('PATIENT')") 
                .and()
            .requestMatchers()
                .antMatchers("/api/doctors/**")
                .and()
            .authorizeRequests()
                .antMatchers("/api/doctors/**").access("hasRole('DOCTOR')"); 
    }
}

************************************更新********** **********************

我正在使用oauth2进行安全保护。我试图在上面的控制器中获取登录用户的用户名。我尝试打印Principal对象,然后得到 @GetMapping("/doctors") public Doctor getDoctor(Authentication user) { System.out.println(user.getName()); return doctorService.getDoctor(user.getName()); }

另一方面,principal.getName()返回null。

我在邮递员中按以下方式发送请求时正在使用标头中的访问令牌。

org.springframework.security.oauth2.provider.OAuth2Authentication@24d14be1: Principal: com.prescribr.rest.service.CustomUserDetails@56d40b2f; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress=0:0:0:0:0:0:0:1, sessionId=<SESSION>, tokenType=bearertokenValue=<TOKEN>; Granted Authorities: ROLE_DOCTOR

CustomUserDetails类:

authorization: bearer theToken

CustomUserDetailsS​​ervice类:

public class CustomUserDetails extends Users implements UserDetails {

    private static final long serialVersionUID = -8170449272852748515L;

    public CustomUserDetails(final Users user) {
        super(user);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        return getRoles()
                .stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        // TODO Auto-generated method stub
        return super.getPassword();
    }

    @Override
    public String getUsername() {
        // TODO Auto-generated method stub
        return super.getEmail();
    }

    @Override
    public boolean isAccountNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isEnabled() {
        // TODO Auto-generated method stub
        return true;
    }

}

用户类别:

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersRepository userRepository;

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

        Optional<Users> usersOptional = userRepository.findByEmail(email);

        Users user = null;

        if(usersOptional.isPresent()) {
            System.out.println(usersOptional.isPresent());
            user = usersOptional.get();
        }else {
            throw new RuntimeException("Email is not registered!");
        }

        return new CustomUserDetails(user);
    }

}

再次感谢!

0 个答案:

没有答案