gpt4 book ai didi

hibernate - 找不到 org.springframework.security.authentication.UsernamePasswordAuthenticationToken 的 AuthenticationProvider

转载 作者:行者123 更新时间:2023-12-02 03:21:08 27 4
gpt4 key购买 nike

我是 spring 4.0 的新手。尝试登录时出现错误“没有找到 org.springframework.security.authentication.UsernamePasswordAuthenticationToken 的 AuthenticationProvider”

这是文件

应用配置类

package com.springmaven.config;

import java.util.Properties;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;



@Configuration
@ComponentScan(basePackages={"com.springmaven.service","com.springmaven.config"})
@EnableTransactionManagement
@EnableJpaRepositories(basePackages="com.springmaven.repository",entityManagerFactoryRef="entityManager")
public class ApplicationConfig {
@Bean(name="datasource")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3308/tms");
dataSource.setUsername("root");
dataSource.setPassword("mindfire");
return dataSource;
}


/**
* @return bean of entity manager
*/
@Bean (name="entityManager")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.springmaven.models" });

JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(getJpaProperties());

return em;
}


/**
* @return Properties used to initialize entityManager Bean
*/
private Properties getJpaProperties() {
Properties properties = new Properties();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.hbm2ddl.auto", "validate");
return properties;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}

/**
* @return a bean of transaction manager
*/




}

DispatherServlet 类

package com.springmaven.config;



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;


@Configuration
@EnableWebMvc
@ComponentScan({"com.springmaven.controller","com.springmaven.service"})
public class DispatcherConfig {

@Bean
public InternalResourceViewResolver getInternalResourceViewResolver()
{
InternalResourceViewResolver internalResourceViewResolver=new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/JSP/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}

安全配置类

package com.springmaven.config;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.core.userdetails.UserDetailsService;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{


@Qualifier("memberDetailsService")
UserDetailsService memberDetailsService;

@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;

@Autowired
CustomSuccessHandler customSuccessHandler;



public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.authenticationProvider(customAuthenticationProvider)
.userDetailsService(memberDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests().antMatchers("/assests/**").permitAll()
.antMatchers("/admin").access("hasRole('ADMIN')")
.antMatchers("/member").access("hasRole('ADMIN') and hasRole('MEMBER')")
.and()
.formLogin().loginPage("/loginPage")
.defaultSuccessUrl("/homePage")
.failureUrl("/loginPage?error")
.usernameParameter("userName").passwordParameter("password")
.and().csrf()
.and()
.logout().logoutSuccessUrl("/loginPage?logout");

}

@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}


@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}

这里是Cutom Authentication Class

package com.springmaven.config;

import java.util.Collection;


import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;


import com.springmaven.account.MemberDetails;
import com.springmaven.models.Employee;

@Component("AuthenticationProvider")
public class CustomAuthenticationProvider implements AuthenticationProvider {


private MemberDetails userService;

public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();

Employee member = (Employee) userService.loadUserByUsername(username);

if (member == null || !member.getEmployeeUserName().equalsIgnoreCase(username)) {
throw new BadCredentialsException("Username not found.");
}

if (!password.equals(member.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}

Collection<? extends GrantedAuthority> authorities = member.getEmpRoles();

return new UsernamePasswordAuthenticationToken(member, password, authorities);

}

@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}


}

UserDetailsS​​ervice 类

package com.springmaven.account;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.springmaven.models.Employee;
import com.springmaven.repo.AccountRepo;
import com.springmaven.models.EmployeeRole;;



@Service("memberDetailsService")
public class MemberDetails implements UserDetailsService {
private final AccountRepo accountRepo;

@Autowired
public MemberDetails(AccountRepo accountRepo) {
this.accountRepo = accountRepo;
}

/* (non-Javadoc)
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
*/
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
Employee member = accountRepo.findByEmployeeUserName(username);
if(member == null) {
throw new UsernameNotFoundException("Could not find Employee " + username);
}

return new CustomEmployeeDetails(member);
}

private final static class CustomEmployeeDetails extends Employee implements UserDetails {


private CustomEmployeeDetails(Employee employee) {
super(employee);
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return AuthorityUtils.createAuthorityList("ROLE_USER");
}

@Override
public String getUsername() {
return getEmployeeUserName();
}

@Override
public boolean isAccountNonExpired() {
return true;
}

@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
return true;
}

private static final long serialVersionUID = 5639683223516504866L;
}

private List<GrantedAuthority> getGrantedAuthorities(Employee employee){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

for(EmployeeRole empRole : employee.getEmpRoles()){
System.out.println("UserProfile : "+empRole);
authorities.add(new SimpleGrantedAuthority("ROLE_"+empRole.getRole()));
}
System.out.print("authorities :"+authorities);
return authorities;
}
}

自定义成功处理程序类

package com.springmaven.config;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{


private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

@Override
protected void handle(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);

if (response.isCommitted()) {
System.out.println("Can't redirect");
return;
}

redirectStrategy.sendRedirect(request, response, targetUrl);
}

protected String determineTargetUrl(Authentication authentication) {
String url="";

Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

List<String> roles = new ArrayList<String>();

for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}


url = "/homePage";

return url;
}

public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}

private boolean isUser(List<String> roles) {
if (roles.contains("ROLE_MEMBER")) {
return true;
}
return false;
}

private boolean isAdmin(List<String> roles) {
if (roles.contains("ROLE_ADMIN")) {
return true;
}
return false;
}

}

员工类

package com.springmaven.models;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.JoinColumn;

import javax.persistence.Table;

import org.springframework.security.core.userdetails.UserDetails;

@Entity
@Table(name="tblemployee")
public class Employee {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="ntEmpID")
private Long accountId;

@Column(name="vcEmployeeUserName")
private String employeeUserName;

@Column(name="vcEmailIdOff")
private String officialEmailID;

@Column(name="vcEmailIdPer")
private String permanentEmailID;

@Column(name="vcEmployeeFirstName")
private String firstName;

@Column(name="vcEmployeeMiddleName")
private String middleName;

@Column(name="vcEmployeeLastName")
private String lastName;

@Column(name="vcPresentAdd")
private String presentAdd;

@Column(name="vcPermanentAdd")
private String permanentAdd;

@Column(name="vcHomePhoneNumber")
private String homeNumber;

@Column(name="vcOfficeNumber")
private String officeNumber;

@Column(name="vcSkills")
private String skills;

@Column(name="vcPassword")
private String password;

@Column(name="fsCV")
private byte[] cvBlob;

@Column(name="fsEmployeePic")
private byte[] picBlob;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "Emlpoyee_PROFILE",
joinColumns = { @JoinColumn(name = "vcEmployeeUserName") },
inverseJoinColumns = { @JoinColumn(name = "ntEmpRoleID") })
private Set<EmployeeRole> empRoles = new HashSet<EmployeeRole>();

public Long getAccountId() {
return accountId;
}

public Set<EmployeeRole> getEmpRoles() {
return empRoles;
}

public void setEmpRoles(Set<EmployeeRole> empRoles) {
this.empRoles = empRoles;
}

public void setAccountId(Long accountId) {
this.accountId = accountId;
}

public String getEmployeeUserName() {
return employeeUserName;
}

public void setEmployeeUserName(String employeeUserName) {
this.employeeUserName = employeeUserName;
}

public String getOfficialEmailID() {
return officialEmailID;
}

public void setOfficialEmailID(String officialEmailID) {
this.officialEmailID = officialEmailID;
}

public String getPermanentEmailID() {
return permanentEmailID;
}

public void setPermanentEmailID(String permanentEmailID) {
this.permanentEmailID = permanentEmailID;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getMiddleName() {
return middleName;
}

public void setMiddleName(String middleName) {
this.middleName = middleName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getPresentAdd() {
return presentAdd;
}

public void setPresentAdd(String presentAdd) {
this.presentAdd = presentAdd;
}

public String getPermanentAdd() {
return permanentAdd;
}

public void setPermanentAdd(String permanentAdd) {
this.permanentAdd = permanentAdd;
}

public String getHomeNumber() {
return homeNumber;
}

public void setHomeNumber(String homeNumber) {
this.homeNumber = homeNumber;
}

public String getOfficeNumber() {
return officeNumber;
}

public void setOfficeNumber(String officeNumber) {
this.officeNumber = officeNumber;
}

public String getSkills() {
return skills;
}

public void setSkills(String skills) {
this.skills = skills;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public byte[] getCvBlob() {
return cvBlob;
}

public void setCvBlob(byte[] cvBlob) {
this.cvBlob = cvBlob;
}

public byte[] getPicBlob() {
return picBlob;
}

public void setPicBlob(byte[] picBlob) {
this.picBlob = picBlob;
}
public Employee() {
}
public Employee(Employee employee) {
this.accountId = employee.accountId;
this.firstName = employee.firstName;
this.lastName = employee.lastName;
this.officialEmailID = employee.officialEmailID;
this.password = employee.password;
}



}

EmployeeRole 类

package com.springmaven.models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.security.core.GrantedAuthority;

@Entity
@Table(name = "tblemproles")
public class EmployeeRole implements GrantedAuthority {

@Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="ntEmpRoleID")
private Long roleId;

@Column(name="vcEmployeeUserName")
private String employeeUserName;

@Column(name="vcRole")
private String role;

public Long getRoleId() {
return roleId;
}

public void setRoleId(Long roleId) {
this.roleId = roleId;
}

public String getEmployeeUserName() {
return employeeUserName;
}

public void setEmployeeUserName(String employeeUserName) {
this.employeeUserName = employeeUserName;
}

public String getRole() {
return role;
}

public void setRole(String role) {
this.role = role;
}

@Override
public String getAuthority() {
// TODO Auto-generated method stub
return this.role;
}

}

扩展 JPA 存储库的 AccountRepo 接口(interface)

package com.springmaven.repo;



import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.springmaven.models.Employee;

@Repository
public interface AccountRepo extends JpaRepository<Employee, Integer>
{
public Employee findByEmployeeUserName(String employeeUserName);
public Employee findByOfficialEmailID(String offEmaiID);
public Employee save(Employee account);

}

错误轨迹

16:13:39.790 [qtp6152563-16] DEBUG o.s.security.web.FilterChainProxy - /loginPage at position 6 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
16:13:39.790 [qtp6152563-16] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/loginpage'; against '/loginpage'
16:13:39.790 [qtp6152563-16] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Request is to process authentication
16:13:39.791 [qtp6152563-16] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken
16:13:39.791 [qtp6152563-16] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Updated SecurityContextHolder to contain null Authentication
16:13:39.791 [qtp6152563-16] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Delegating to authentication failure handler org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@1a33ab3
16:13:39.791 [qtp6152563-16] DEBUG o.s.s.w.a.SimpleUrlAuthenticationFailureHandler - Redirecting to /loginPage?error
16:13:39.805 [qtp6152563-16] DEBUG o.s.s.web.DefaultRedirectStrategy - Redirecting to '/loginPage?error'

我刚刚开始在 Spring 4.0 中学习和实现 Spring Security

请帮助我。

最佳答案

我认为您的“支持”方法是错误的。应该是

@Override
public boolean supports(Class<? extends Object> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}

关于hibernate - 找不到 org.springframework.security.authentication.UsernamePasswordAuthenticationToken 的 AuthenticationProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33342882/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com