- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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);
}
}
UserDetailsService 类
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/
我正在尝试在 Windows 上运行的小于 1GB 的 VM 上设置 YouTrack 和 TeamCity。使用率将非常低(用户和请求)。这是一个 POC 环境,如果它有效,我可能会将它推送到一个超
所以我在尝试使用 FORFILES 解决这个问题时遇到了麻烦。我正在尝试获取不超过 4 天的文件。所以基本上少于 4 天。然而,这似乎不太可能,因为/d -4 获取所有 4 天或更早的项目。 以下是我
如何从下面的 events 表中选择小于 15 分钟前创建的 events? CREATE TABLE events ( created_at timestamp NOT NULL DEFAU
Google Analytics Realtime提供 rt:minutesAgo ,可以过滤查询。 然而,它是一个维度而不是一个度量标准,<=不能在过滤器中使用。 假设我想在最后 n 分钟内获得一些
iOS 核心数据 - 严重的应用程序错误 - 尝试插入 nil 你好, 我的应用程序实际上运行稳定,但在极少数情况下它会崩溃并显示此错误消息... 2019-04-02 20:48:52.437172
我想制作一个 html div 以快速向右移动(例如不到 1 秒)并消失。然后1秒后再次直接出现在这个过程最开始div的位置。此过程将由单击按钮并重复 10 次触发。 我试图在 CSS 中使用过渡属性
我发现使用 TimeTrigger 是 Windows 10 (UWP) 上计划后台任务的方式。但是看起来我们需要给出的最小数字是 15 分钟。只是想知道,即使我们安排它在接下来的 1 分钟内运行,警
我必须在 1 秒内在屏幕上打印 2^20 行整数 printf 不够快,还有其他易于使用的快速输出替代方法吗? 每一行只包含 1 个整数。 我要求它用于竞争性编程问题,我必须将其源代码提交给法官。 最
我是一名优秀的程序员,十分优秀!