【问题标题】:How to authenticate user manually in spring boot?如何在 Spring Boot 中手动验证用户身份?
【发布时间】:2017-06-13 14:00:58
【问题描述】:

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

【问题讨论】:

  • 使用基于 spring-security 角色的授权。 this link 可能对你有所帮助
  • @harshavmb 非常感谢。您的链接非常有帮助。

标签: java spring spring-boot spring-security


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2017-11-02
    • 2019-11-22
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    相关资源
    最近更新 更多