在 Spring 中实现这种身份验证有多种选择。
案例 1:- 如果您正在构建 REST 服务,那么您可以通过以下方式实现安全性:
i) - 您可以使用基本身份验证来验证您的用户。
ii) - 您可以使用 OAuth2 对您的用户进行身份验证和授权。
案例 2:如果您正在构建 Web 应用程序
i) - 您可以使用身份验证令牌(在单页应用程序 SPA 的情况下)
ii) - 您可以使用基于会话的身份验证(传统登录表单等)
我猜你处于初学者模式,所以我建议你首先通过登录表单了解 Web 应用程序中的控制流用户身份验证。所以让我们来看看一些代码。
我假设您已经设置了一个基本的 spring 项目,现在您正在实施安全性。
USER - 用户表的休眠实体;
ROLE - 角色表的休眠实体
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthProvider customAuthProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
// everyone is allowed tp view login page
http.authorizeRequests().antMatchers("/login").permitAll().and();
http.authorizeRequests().antMatchers("custom_base_path" + "**").authenticated().and().
formLogin().loginPage("/loginForm).loginProcessingUrl("/loginUser")
.usernameParameter("username").passwordParameter("password")
.defaultSuccessUrl("custom_base_path+ "home", true);
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
}
//CustomAuthProvider
@Component
public class CustomAuthentiationProvider implements AuthenticationProvider{
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userid = authentication.getName();
String password = authentication.getCredentials().toString();
Authentication auth = null;
try {
//write your custom logic to match username, password
boolean userExists = your_method_that_checks_username_and_password
if(userExists ){
List<Role> roleList= roleDao.getRoleList(userid);
if (roleList == null || roleList.isEmpty()) {
throw new NoRoleAssignedException("No roles is assigned to "+userid);
}
auth = new UsernamePasswordAuthenticationToken(userid, password,getGrantedAuthorities(roleList));
}
} catch (Exception e) {
log.error("error", e);
}
return auth;
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
public List<GrantedAuthority> getGrantedAuthorities(List<Role> roleList) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Role role : roleList) {
authorities.add(new SimpleGrantedAuthority(role.getRoleName());
}
return authorities;
}
}
注意: 请考虑这些代码以了解身份验证的逻辑。不要认为是完美的代码(不适用于生产环境)。您可以随时联系我,我会向您提供更多相关建议。