春季启动-尝试从mySQL DB认证用户-需要授予权限的文本表示形式

时间:2018-10-17 18:56:38

标签: java spring hibernate spring-security

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

org.springframework.security.authentication.InternalAuthenticationServiceException:必须授予授权的文本表示形式

这是我的 SecurityConfig

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

UserDetailsS​​ervice

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

UserInfoDao

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();
}   
}     

我真的不明白为什么我仍然会收到授权的文本表示形式。
我已经在数据库中的“角色”列中添加了适当的角色:ROLE_ADMINROLE_USER,这里的一切似乎都很好。

一些日志:

  

2018-10-17 20:05:29.932信息15968 --- [nio-8090-exec-1]   o.a.c.c.C. [Tomcat]。[localhost]。[/]:初始化Spring   FrameworkServlet'dispatcherServlet'2018-10-17 20:05:29.932信息   15968-[nio-8090-exec-1] o.s.web.servlet.DispatcherServlet:   FrameworkServlet'dispatcherServlet':初始化已开始   2018-10-17 20:05:29.938 INFO 15968 --- [nio-8090-exec-1]   o.s.web.servlet.DispatcherServlet:FrameworkServlet   'dispatcherServlet':初始化在6毫秒内完成2018-10-17   20:05:37.694 INFO 15968 --- [nio-8090-exec-3]   o.h.h.i.QueryTranslatorFactoryInitiator:HHH000397:使用   ASTQueryTranslatorFactory 2018-10-17 20:05:37.701调试15968 ---   [nio-8090-exec-3] org.hibernate.SQL:       选择           userinfo0_.userid作为userid1_1_,           userinfo0_.enabled为enabled2_1_,           userinfo0_.password作为password3_1_,           userinfo0_.role作为角色4_1_       从           tuserid userinfo0_       哪里           userinfo0_.userid =?           和userinfo0_.enabled =? 2018-10-17 20:05:37.701跟踪15968-[nio-8090-exec-3] ohtype.descriptor.sql.BasicBinder:绑定参数[1]为[VARCHAR]-[kudelam] 2018-10- 17 20:05:37.701   跟踪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]   w.a.UsernamePasswordAuthenticationFilter:发生内部错误   在尝试验证用户身份时。

     

org.springframework.security.authentication.InternalAuthenticationServiceException:   必须授予授权的文本表示形式

可以请您看看并切细一点吗?

1 个答案:

答案 0 :(得分:0)

以这种方式代替

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);