2017-09-06 143 views
0

我使用的是春天启动安全性,帮助我作出认证...春季启动基本身份验证

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-security</artifactId> 
</dependency> 



@Configuration 
@EnableWebSecurity 
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
     .cors().and().csrf().disable().authorizeRequests() 
     .anyRequest().authenticated().and().httpBasic(); 
    } 
} 

我有一个休息的服务,使登录(我的控制器上)那是一个POST请求,我送电子邮件和密码,我喜欢使用此服务进行身份验证...

但我是新的春季引导/ Java ...可以有人帮助我做出正确的方式吗?

谢谢。

回答

0

我会从阅读spring启动安全性文档开始。在下面你会找到一个链接。

https://docs.spring.io/spring-security/site/docs/current/guides/html5/helloworld-boot.html

+0

我看到很多使用此实现的:@Autowired \t公共无效configureGlobal(AuthenticationManagerBuilder AUTH)抛出异常{ \t \t权威性 \t \t \t .inMemoryAuthentication() \t \t \t \t .withUser(“user”)。password(“password”)。roles(“USER”); \t} ...但我想用我自己的服务 –

0

您需要允许访问登录端点(至少)。例如。

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.authorizeRequests().antMatchers("/login", "/error").permitAll() 
      .antMatchers("/**").authenticated().and().exceptionHandling() 
      .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")); 
} 

如果我是你,我会删除@EnableWebSecurity(并让Spring引导做的工作),以及。然后在登录端点中,你需要设置安全上下文,例如

@PostMapping 
public void authenticate(@RequestParam Map<String, String> map, 
     HttpServletRequest request, HttpServletResponse response) throws Exception { 
    Authentication result = authService.authenticate(map.get("username"), map.get("password")); 
    SecurityContextHolder.getContext().setAuthentication(result); 
    handler.onAuthenticationSuccess(request, response, result); 
} 

authService应该抛出BadCredentialsException如果用户无法进行身份验证。下面是我在博客中使用一次一个示例应用程序:https://github.com/dsyer/mustache-sample/blob/7be8459173d0b65b6d44d05f86e581d358ea9b2e/src/main/java/com/example/DemoApplication.java#L177

2

变化SpringSecurityConfig.java添加方法如下图所示

@Configuration 
    @EnableWebSecurity 
    public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { 
    @Autowired 
    private UserAuthenticationService userAuthenticationService; 

    @Autowired 
    private CustomAuthenticationProvider authenticationProvider; 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth.authenticationProvider(this.authenticationProvider).userDetailsService(this.userAuthenticationService); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
     .cors().and().csrf().disable().authorizeRequests() 
     .anyRequest().authenticated().and().httpBasic(); 
    }} 

创建CustomAuthenticationProvider。

@Component 
public class CustomAuthenticationProvider implements AuthenticationProvider { 

    @Autowired 
    private UserAuthenticationService userAuthenticationService; 

    @Override 
    public boolean supports(Class<?> authentication) { 
     return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); 
    } 

    @Override 
    public Authentication authenticate(Authentication authentication) throws AuthenticationException { 
     String emailId = authentication.getName(); 
     String password = (String) authentication.getCredentials(); 
     UserDetails user = this.userAuthenticationService.loadUserByUsername(emailId); 
     if (user == null) { 
      throw new UsernameNotFoundException("Username not found."); 
     } 
     //Your password encoder here 
     if (!password.equals(user.getPassword())) { 
      throw new UsernameNotFoundException("Wrong password."); 
     } 
     Collection<? extends GrantedAuthority> authorities = user.getAuthorities(); 
     return new UsernamePasswordAuthenticationToken(user, password, authorities); 
    }} 

创建自定义UserService

@Service 
public class UserAuthenticationService implements UserDetailsService { 
    @Autowired 
    private UserRepository userRepository; 

    @Override 
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { 
     User user = userRepository.findByEmailAddressWithRole(email); 
     if (user == null) { 
      throw new UsernameNotFoundException("Username not found for " + email); 
     } 
     List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); 
     for (Role roles : user.getRoles()) { 
      grantedAuthorities.add(new SimpleGrantedAuthority(roles.getRoleName())); 
     } 
     return new UserAuthenticationWrapperDto(user.getId(), user.getEmailAddress(), user.getPassword(), 
       user.getUserType(), user.getCompany().getId(), grantedAuthorities,user.getName()); 
    }}