2017-09-06 189 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()); 
    }} 
相關問題