Spring Boot 基本认证
Posted
技术标签:
【中文标题】Spring Boot 基本认证【英文标题】:Spring boot basic authentication 【发布时间】:2018-02-14 08:17:09 【问题描述】:我正在使用 Spring Boot Security 来帮助我进行身份验证...
<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();
我有一项用于登录(在我的控制器上)的休息服务,这是我发送电子邮件和密码的发布请求,我喜欢使用此服务进行身份验证...
但是我是 spring-boot / java 的新手...有人可以帮我做正确的方法吗?
谢谢。
【问题讨论】:
【参考方案1】:在 SpringSecurityConfig.java 中更改 add 方法,如下所示
@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);
创建自定义用户服务
@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());
【讨论】:
【参考方案2】:您需要允许访问登录端点(至少)。例如。
@Override
protected void configure(HttpSecurity http) throws Exception
http.authorizeRequests().antMatchers("/login", "/error").permitAll()
.antMatchers("/**").authenticated().and().exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
如果我是你,我也会删除 @EnableWebSecurity
(让 Spring Boot 完成它的工作)。然后在登录端点中,您需要设置安全上下文,例如
@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
【讨论】:
你能不能也看看我的问题? ***.com/questions/66903591/…以上是关于Spring Boot 基本认证的主要内容,如果未能解决你的问题,请参考以下文章
spring boot整合jwt 实现前后端分离登录认证及授权
Spring Boot使用AOP实现REST接口简易灵活的安全认证