Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在spring boot中手动验证用户?_Java_Spring_Spring Boot_Spring Security - Fatal编程技术网

Java 如何在spring boot中手动验证用户?

Java 如何在spring boot中手动验证用户?,java,spring,spring-boot,spring-security,Java,Spring,Spring Boot,Spring Security,我有两个表“user”和“role”。我想创建一个登录api(例如“/login”),它将用户名和密码作为json数据。我想检查给定的凭据是否是有效的凭据,如果是,那么我想将该用户设置为经过身份验证的用户,以便他/她可以拥有受保护的资源。我是spring boot framework的新手,不知道怎么做。我已经阅读了官方文档,但找不到任何资源。有人能帮我吗?在spring中实现这种身份验证有很多选择 案例1:-如果您正在构建REST服务,则可以通过以下方式实现安全性: i) -您可以使用基本身份

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

在spring中实现这种身份验证有很多选择

案例1:-如果您正在构建REST服务,则可以通过以下方式实现安全性:

i) -您可以使用基本身份验证对用户进行身份验证

ii)-可以使用OAuth2对用户进行身份验证和授权

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

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

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

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

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

用户-用户表的休眠实体; 角色-角色表的休眠实体

@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;
}
}
@配置
@启用Web安全性
公共类WebSecurityConfig扩展了WebSecurityConfigureAdapter{
@自动连线
私人CustomAuthProvider CustomAuthProvider;
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
//每个人都可以查看登录页面
http.authorizeRequests().antMatchers(“/login”).permitAll()和();
http.authorizeRequests().antMatchers(“自定义基本路径”+“**”).authorized()和()。
formLogin().loginPage(“/loginForm).loginProcessingUrl(“/loginUser”)
.usernameParameter(“用户名”).passwordParameter(“密码”)
.defaultSuccessUrl(“自定义基本路径+“主路径”,true);
@自动连线
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)引发异常{
auth.authenticationProvider(customAuthProvider);
}
//CustomAuthProvider
@组成部分
公共类CustomAuthenticationProvider实现AuthenticationProvider{
@凌驾
公共身份验证(身份验证)引发AuthenticationException{
字符串userid=authentication.getName();
字符串密码=authentication.getCredentials().toString();
身份验证auth=null;
试一试{
//编写自定义逻辑以匹配用户名、密码和密码
boolean userExists=检查用户名和密码的方法
如果(用户存在){
List roleList=roleDao.getRoleList(userid);
if(roleList==null | | roleList.isEmpty()){
抛出新的NoRoleAssignedException(“没有为“+userid”分配任何角色);
}
auth=新用户名PasswordAuthenticationToken(用户标识、密码、GetGrantedAuthories(角色列表));
}
}捕获(例外e){
日志错误(“错误”,e);
}
返回auth;
}
@凌驾
公共布尔支持(类身份验证){
返回authentication.equals(UsernamePasswordAuthenticationToken.class);
}
公共列表GetGrantedAuthority(列表角色列表){
列表权限=新建ArrayList();
for(角色:roleList){
add(新的SimpleGrantedAuthority(role.getRoleName());
}
返回当局;
}
}

<强>注:< /强>请考虑这些代码来理解认证的逻辑。不要认为是完美的代码(不是生产Env)。。您可以随时ping我,我会向您推荐更多信息。

使用基于spring security角色的授权。这可能会帮助您解决一些问题extent@harshavmb非常感谢。你的链接非常有用。