java - 如何在 Spring Boot 中手动验证用户身份?

标签 java spring spring-boot spring-security

我有两个表“user”和“role”。我想创建一个登录 api(例如“/login”),它将用户名和密码作为 json 数据。我想检查给定的凭据是否是有效的凭据,如果是,那么我想将用户设置为经过身份验证的用户,以便他/她可以拥有 protected 资源。我是 Spring Boot 框架的新手,我不知道该怎么做。我已阅读官方文档,但找不到任何资源。有人可以帮助我吗?

最佳答案

您有多种选择在 Spring 中实现此类身份验证。

情况 1:-如果您正在构建 REST 服务,那么您可以通过以下方式实现安全性:

i) - 您可以使用基本身份验证来验证您的用户。

ii) - 您可以使用 OAuth2 来验证和授权您的用户。

情况 2:如果您正在构建 Web 应用程序

i) - 您可以使用身份验证 token (在单页应用程序 SPA 的情况下)

ii) - 您可以使用基于 session 的身份验证(传统登录表单等)

我猜您处于初学者模式,所以我建议您首先通过登录表单了解网络应用程序中的控制流用户身份验证。让我们看一下一些代码。

我假设您已经设置了一个基本的 Spring 项目,现在正在实现安全性。

USER - 用户表的 Hibernate 实体; ROLE - 角色表的 Hibernate 实体

@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;
}
}

注意: 请考虑这些代码以了解身份验证的逻辑。不要认为是完美的代码(不适用于生产环境)。您可以随时联系我,我会向您提供更多相关建议。

关于java - 如何在 Spring Boot 中手动验证用户身份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511357/

相关文章:

java - 无法准备声明;嵌套异常是 org.hibernate.exception.JDBCConnectionException : could not prepare statement

java - Spring Boot 应用程序中的两个数据源

java - Apache Parquet 数据存储引擎?

java - spring是否提供2个mvc平台,grails和spring mvc?

java - Java Spring 在无效的 HttpSession 上返回错误

java - 通过创建 REST 端点使用 spring-boot 发送电子邮件

java - @Primary JpaRepository 不用于@Autowired

java - 从 cmd 运行 JavaFX

java - 使用 Jackson 将 ebean 映射到 json 时如何避免无限循环引用?

java - 如何检查 netbeans 中的编译器和运行时?