当前位置: 首页 > 知识库问答 >
问题:

Spring Boot-尝试从mySQL DB验证用户身份-需要一个授权文本表示

宦翔
2023-03-14

2018-10-17 20:05:37.715错误15968---[nio-8090-exec-3]W.A.UsernamePasswordAuthenticationFilter:尝试对用户进行身份验证时出现内部错误。

package com.project.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@ComponentScan(basePackages= {"com.project.*"})
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAppUserDetailsService myAppUserDetailsService;    
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers("/app/secure/**").hasAnyRole("ADMIN","USER")
    .and().formLogin()  //login configuration
            .loginPage("/app/login")
            .loginProcessingUrl("/app-login")
            .usernameParameter("userName")
            .passwordParameter("password")
            .defaultSuccessUrl("/app/secure/temployee-details") 
    .and().logout()    //logout configuration
    .logoutUrl("/app-logout") 
    .logoutSuccessUrl("/app/login")
    .and().exceptionHandling() //exception handling configuration
    .accessDeniedPage("/app/error");
} 
    @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
          auth.userDetailsService(myAppUserDetailsService).passwordEncoder(passwordEncoder);
}
} 
package com.project.config;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.project.dao.IUserInfoDAO;
import com.project.entity.UserInfo;
@ComponentScan(basePackages= {"com.project.*"})
@Service
public class MyAppUserDetailsService implements UserDetailsService {
@Autowired
private IUserInfoDAO userInfoDAO;
@Override
public UserDetails loadUserByUsername(String userName)
        throws UsernameNotFoundException {
    UserInfo activeUserInfo = userInfoDAO.getActiveUser(userName);
    GrantedAuthority authority = new SimpleGrantedAuthority(activeUserInfo.getRole());
    UserDetails userDetails = (UserDetails)new User(activeUserInfo.getUserName(),
            activeUserInfo.getPassword(), Arrays.asList(authority));
    return userDetails;
}
}
package com.project.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.project.entity.TEmployee;
import com.project.entity.UserInfo;
@ComponentScan(basePackages= {"com.project.*"})
@Repository
@Transactional
public class UserInfoDAO implements IUserInfoDAO {
@PersistenceContext 
private EntityManager entityManager;
public UserInfo getActiveUser(String userName) {
    UserInfo activeUserInfo = new UserInfo();
    short enabled = 1;
    List<?> list = entityManager.createQuery("SELECT u FROM UserInfo u WHERE userName=?1 and enabled=?2")
            .setParameter(1, userName).setParameter(2, enabled).getResultList();
    if(!list.isEmpty()) {
        activeUserInfo = (UserInfo)list.get(0);
    }
    return activeUserInfo;
}
@SuppressWarnings("unchecked")
@Override
public List<TEmployee> getAllUserEmployees() {
    String hql = "FROM TEmployee as t ORDER BY t.employee_id";
    return (List<TEmployee>) entityManager.createQuery(hql).getResultList();
}   
}     

某些日志:

2018-10-17 20:05:29.932信息15968---[nio-8090-exec-1]O.A.C.C.C.[Tomcat].[localhost].[/]:初始化Spring FrameworkServlet“Dispatcher Servlet”O.s.web.servlet.DispatcherServlet:FrameworkServlet“Dispatcher Servlet”:初始化开始2018-10-17 20:05:29.938信息15968---[nio-8090-exec-1]O.s.web.servlet.DispatcherServlet:FrameworkServlet“Dispatcher Servlet”:初始化在6毫秒内完成2018-10-17和userinfo0_.enabled=?2018-10-17 20:05:37.701 TRACE 15968---[nio-8090-exec-3]O.H.Type.Descriptor.Sql.BasicBinder:绑定参数[1]为[VARCHAR]-[kudelam]2018-10-17 20:05:37.701 TRACE 15968----[nio-8090-exec-3]O.H.Type.Descriptor.Sql.BasicBinder:绑定参数[2]为[SMALLINT]-[1]2018-10-17 20:05:37.715错误15968---[nio-8090-exec-3]

org.springframework.security.authentication.internalauthenticationserviceexception:需要授予的权限文本表示

你能看一看,在这个上面擦点光吗?

共有1个答案

惠诚
2023-03-14

用这种方法试试,而不是

GrantedAuthority authority = new SimpleGrantedAuthority(activeUserInfo.getRole());
UserDetails userDetails = (UserDetails)new User(activeUserInfo.getUserName(),
        activeUserInfo.getPassword(), Arrays.asList(authority));

Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority(activeUserInfo.getRole()));


return new org.springframework.security.core.userdetails.User(activeUserInfo.getUsername(),
                                                              activeUserInfo.getPassword(),
                                                              grantedAuthorities);
 类似资料:
  • OAuth术语已经困扰我很久了。OAuth授权是像一些人建议的那样,还是认证? 如果我错了,请纠正我,但我一直认为授权是允许某人访问某个资源的行为,而OAuth似乎没有任何实际允许用户访问给定资源的实现。OAuth实现所讨论的都是为用户提供一个令牌(签名的,有时是加密的)。然后,每次调用都会将该令牌传递到后端服务endpoint,在后端服务endpoint上检查该令牌的有效性,这也不是OAuth的

  • 我有一个已经完成的j2ee(jsf、cdi、jpa)应用程序,它完美地使用了ApacheShiro,它工作得非常好,我喜欢Shiro注释(hasRole、hasPermission等)。 现在,该项目还必须能够通过SiteMinder进行身份验证,我的问题是: 我如何设置一个领域来处理SiteMinder身份验证而不丢失Shiro授权(似乎SiteMinder会在HTTP头中给我用户名和Rolen

  • 我们正在尝试找出IPC身份验证和授权的最佳实践。我会解释的。我们有一个基于微服务的体系结构SaaS和一个专门的认证服务。该服务负责执行身份验证和管理身份验证令牌(JWT)。 现在的问题是如何验证和授权由其他服务发起的请求(没有特定用户的上下文)? 我们是否应该为每个服务生成一个专用用户,并像对待系统中的任何其他用户一样对待它(具有适当的权限)? 我们是否应该在服务之间部署“硬编码”/动态令牌? 还

  • 我正在尝试使用基本身份验证获取url。我设置用户/密码如下所示。同样的凭证在邮递员中工作。 我认为凭据设置不正确。这里怎么了?错误:

  • 问题内容: 我收到错误 NOAUTH必需的身份验证 。我的laravel版本是5.3,我正在使用predis 1.1.1连接redis。 在etc / redis / redis.conf中,我有: 在.env文件中 在config / database.php中,我有: 我通过以下方式连接redis: 并像这样使用它: 因此,当我注释掉并将密码发送为null时,它可以工作,但在密码到位后却无法工