Spring security使用自定義登入介面且顯示登入異常資訊的例子
阿新 • • 發佈:2019-01-28
eclipse中的工程結構:
1、配置Maven的pom檔案:
2、使用註解的方式配置Spring Security:<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringSecurity</groupId> <artifactId>SpringSecurity</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringSecurity Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>SpringSecurity</finalName> </build> </project>
package com.config; import org.springframework.beans.factory.annotation.Autowired; 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.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.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests(). antMatchers("/secure/**").//匹配URL access("hasRole('ROLE_ADMIN')").//驗證登入者角色 and().formLogin(). //login configuration loginPage("/customLogin.jsp"). failureUrl("/customLogin.jsp?failed=true"). //配置登入失敗URL loginProcessingUrl("/appLogin"). usernameParameter("app_username"). passwordParameter("app_password"). defaultSuccessUrl("/secure/home"). and().logout(). //logout configuration logoutUrl("/appLogout"). logoutSuccessUrl("/customLogin.jsp"); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("ram").password("ram123").roles("ADMIN"); } }
3、使用註解配置SpringMVC
package com.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan("com") //掃描資料夾內的類以生產beans @Import(SecurityConfig.class) //引入Spring Security 配置類 @EnableWebMvc public class AppConfig { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/secure/"); resolver.setSuffix(".jsp"); return resolver; } }
4、建立自定義登入介面:
customLogin.jsp:
<%@ page language="java" contentType="text/html; charset=gbk" pageEncoding="gbk"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="true" %> <!--如session設定為false,SPRING_SECURITY_LAST_EXCEPTION會始終為null-->
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Spring 4 Security Example</title>
</head>
<body>
<h3>Spring 4 Security Example</h3>
<font color="red">
<c:if test="${param.failed==true }">
<div>login failed,try again!</div>
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION }">
<c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/>
</c:if>
</c:if>
</font>
<form action="<%=request.getContextPath()%>/appLogin" method="POST">
Enter UserName: <input type="text" name="app_username"/><br/><br/>
Enter Password: <input type="password" name="app_password"/> <br/><br/>
<input type="submit" value="Login"/>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
<body>
</html>
home.jsp:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Spring 4 Security Example</title>
</head>
<body>
<h3>Spring 4 Security Example</h3>
Student Name: ${stdName}
<form action="<%=request.getContextPath()%>/appLogout" method="POST">
<input type="submit" value="Logout"/>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</body>
</html>
output.jsp:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Spring 4 Security Example</title>
</head>
<body>
<h3>Spring 4 Security Example</h3>
Student Name: ${stdName}
<form action="<%=request.getContextPath()%>/appLogout" method="POST">
<input type="submit" value="Logout"/>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</body>
</html>
student.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ page isELIgnored="false" %>
<html>
<head><title>Spring 4 Security Example</title></head>
<body>
<h3>Spring 4 Security Example </h3>
<form:form action="result" method="POST" commandName="student">
<form:input path="stdId"/> <br/>
<input type="submit" value="Submit">
</form:form>
</body>
</html>
程式碼下載:https://github.com/angleBeibei/SpringSecurity
參考資料:http://www.concretepage.com/spring-4/spring-4-mvc-security-custom-login-form-and-logout-example-with-csrf-protection-using-annotation-and-xml-configuration