gpt4 book ai didi

java - Spring MVC Hibernate Spring Security 登录

转载 作者:行者123 更新时间:2023-11-29 07:35:58 25 4
gpt4 key购买 nike

我正在尝试通过登录使用 spring security。

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<form:form action="j_spring_security_check" method="POST" modelAttribute="loginForm">
<table>
<tr>
<td colspan="2" align="center">Already have an account - Login</td>
</tr>
<tr>
<td>Email</td>
<td><form:input path="emailID" /> <form:errors path="emailID" class="error" /></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /> <form:errors path="password" class="error" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<a href="${pageontext.request.contextPath }/forgotpassword">Forgot Password</a>
</td>
</tr>
</table>
</form:form>
<span class="error">${loginMessage}</span>

spring-security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">

<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_admin')" />

<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login
login-page="/login"
default-target-url="/index"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf />
</http>

<beans:bean id="userAuthenticationProviderImpl" class="com.pir.authentication.UserAuthenticationProviderImpl" />

<authentication-manager>
<authentication-provider user-service-ref="userAuthenticationProviderImpl" >
<password-encoder hash="plaintext" />
</authentication-provider>
</authentication-manager>

</beans:beans>

UserAuthenticationProviderImpl.java

@Component(value = "authenticationProvider")
public class UserAuthenticationProviderImpl implements
UserAuthenticationProvider {

UserFunctionsService userFunctionsService;

@Autowired(required=true)
@Qualifier(value="userFunctionsService")
public void setUserFunctionsService(UserFunctionsService userFunctionsService)
{
this.userFunctionsService = userFunctionsService;
}

/* (non-Javadoc)
* @see com.pir.authentication.UserAuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
*/
@Override
public Authentication authenticate(Authentication authentication) {
// TODO Auto-generated method stub

Users users = (Users) this.userFunctionsService.getUserDetails(authentication.getPrincipal().toString());

if(users == null)
throw new UsernameNotFoundException(String.format("Invalid credentials", authentication.getPrincipal()));

String suppliedPasswordHash = authentication.getCredentials().toString();

if(users.getPassword().equals(suppliedPasswordHash)){
throw new BadCredentialsException("Invalid credentials");
}
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(users, null);

return token;
}

}

用户.java

@Entity
@Table(name = "users")
public class Users {

@NotNull
@Id
@Column(name = "userID")
private int userID;

@NotNull
@Size(min=3, max=50)
@Pattern(regexp = ".+@.+\\.[a-z]+")
@Column(name = "emailID")
private String emailID;

@NotNull
@Size(min=3, max=50)
@Column(name = "firstName")
private String firstName;

@NotNull
@Size(min=3, max=50)
@Column(name = "lastName")
private String lastName;

@NotNull
@Size(min=3, max=50)
@Column(name = "password")
private String password;

@NotNull
@Column(name = "mobileNo")
private String mobileNo;


@Column(name = "imageURL")
private String imageURL;

@NotNull
@DateTimeFormat(pattern="MM/dd/yyyy")
@Column(name = "dateOfBirth")
private String dateOfBirth;

@NotNull
@Column(name = "gender")
private String gender;

@NotNull
@Column(name = "userType")
private String userType;

@Lob
private MultipartFile image;

//getters and setters
}

pir-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"
xmlns:mvc="http://www.springframework.org/schema/mvc">

<context:annotation-config />

<context:component-scan base-package="com.pir" />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="myTransactionManager" />

<bean id="myTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="userFunctionsDAO" class="com.pir.dao.UserFunctionsDAOImpl" />
<bean id="userFunctionsService" class="com.pir.service.UserFunctionsServiceImpl" />

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/pir"
p:username="root"
p:password="user" />

<bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>

</beans>

当我尝试登录时,我希望登录成功或失败,但它给出了 HTTP Status 404 - 错误。这是我第一次尝试实现 spring security,所以对它了解不多。我在这段代码中做错了什么?

最佳答案

你还记得在 web.xml 中设置 spring 安全过滤器链吗?

<!--  Spring security filter -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

这可能是原因,但您的提供程序实现中存在一些错误。

 if(users.getPassword().equals(suppliedPasswordHash)){
throw new BadCredentialsException("Invalid credentials");
}
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(users, null);

首先if里的条件不对,这个应该正好相反:

 if(!users.getPassword().equals(suppliedPasswordHash)){
throw new BadCredentialsException("Invalid credentials");
}

创建 UsernamePasswordAuthenticationToken 的下一行必须不同,一旦用户通过身份验证,您必须在调用构造函数时创 build 置 GrantedAuthorities 的 token 。如果user中的userType字段是匹配spring-security中指定的ROLE_admin的Authority,则必须做更多这样的事情:

Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(user.getUserType()));
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(users, null, authorities);

如果您不这样做,您的提供者将返回一个未授予访问权限的授权对象

关于java - Spring MVC Hibernate Spring Security 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35716136/

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