2017-06-13 59 views
-2

我有两个表'用户'和'角色'。我想创建一个登录api(例如'/ login'),它将用户名和密码作为json数据。我想检查给定的凭证是否是有效的凭证,如果是,那么我想将用户设置为已认证的用户,以便他/她可以拥有受保护的资源。我是Spring引导框架的新手,我不知道该怎么做。我已阅读官方文档,但找不到任何资源。有人可以帮我解决这个问题吗?如何在春季开机时手动验证用户?

+1

使用基于弹簧安全角色的授权。 [此链接](http://www.baeldung.com/role-and-privilege-for-spring-security-registration)可能会在一定程度上帮助你 – harshavmb

+0

@harshavmb非常感谢你。你的链接非常有帮助。 –

回答

0

在Spring中你有很多选择来实现这种认证。

案例1: -如果您正在构建REST服务,那么您可以在以下几个方面实现安全性:

我) - 你可以使用基本的身份验证您的用户进行身份验证。

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

案例2:如果您正在构建Web应用程序

我) - 您可以使用身份验证令牌(在单页应用SPA的情况下)

II) - 你可以使用基于会话的身份验证(传统登录表单和所有)

我猜你是初学者模式,所以我建议你首先通过登录表单了解Web应用程序中的控制流用户身份验证。所以我们来看看一些代码。

我假设你已经设置了一个基本的弹簧项目,现在你正在实现安全。

USER - 用户表的Hibernate实体; 作用 - 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; 
} 
} 

注:请考虑这些代码,了解认证的逻辑。不要考虑为完美的代码(不适用于生产环境)。你随时可以给我打电话,我会向你提供更多的建议。

+0

为什么没有投票?即使在接受答案后 –