Single sign-on solution -CAS

 

Goal 1: Build a single sign-on server and develop a single sign-on client

Goal 2: Configure the CAS authentication data source

Goal 3: Change the CAS login page

Goal 4: master CAS integration with SpringSecurity

Goal 5: Complete user-centric single sign-on (SSO)

Introduction to open Source Single sign-on System CAS

What is single sign-on

Single Sign On, or SSO for short, is one of the more popular solutions for enterprise business integration. SSO is defined as one login in multiple applications that allows users to access all trusted applications.

At present, there are many subsystems in our system, and these subsystems are deployed in different servers, so it is impossible to solve the problem by using the traditional session method, and we need to use the relevant single sign-on technology to solve the problem.

 

1.2 What is CAS

CAS is an open source project initiated by Yale University, aiming to provide a reliable single sign-on method for Web application systems. CAS officially became a project of JA-SIG in December 2004. CAS has the following characteristics:

[1] Open source enterprise single sign-on solution.

[2] CAS Server is a Web application that needs to be deployed independently.

[3] CAS Client supports a wide range of clients (here referring to various Web applications in the single sign-on system), including Java,.NET, PHP, Perl, Apache, uPortal, Ruby, etc.

Structurally, the CAS consists of the CAS Server and CAS Client. The CAS Server must be deployed independently to authenticate users. The CAS Client processes the access requests to protected resources on the Client and redirects the access requests to the CAS Server. The following figure shows the basic CAS protocol process:

 

The SSO SSO access process consists of the following steps:

1. Access services: The SSO client sends a request to access service resources provided by the application system.

2. Directed authentication: The SSO client redirects user requests to the SSO server.

3. User authentication: User identity authentication.

4. Ticket issuance: The SSO server generates a random Service Ticket.

5. Verify tickets: The SSO server verifies the validity of the Ticket Service Ticket and allows clients to access the Service.

6. Transfer user information: After the SSO server authenticates the ticket, the SSO server transfers the user authentication result to the client.

1.3 CAS Server Deployment

The Cas server is essentially a WAR package.

In the resource cas-source cas-server-4.0.0-release cas-server-4.0.0modules directory

War Rename the cas-server-webapp-4.0.0.war to cas.war and add it to the Webapps in the Tomcat directory. Enable tomcat to automatically decompress the WAR package. The browser type http://localhost:8080/cas/login, can see the login page

Don’t hate this page ugly, we can improve its appearance level later. Focus on functionality for a while.

There is a fixed user name and password casuser /Mellon

After the login is successful, a dialog box is displayed indicating that the login is successful

 

Configure the CAS server

Port to modify

If we do not want to use port 8080 to access CAS, we can change the port

  1. Example Change the TOMCAT port

Open the tomcat directory conf\server.xml to find the following configuration

 

Change port 8080 to 9100

  1. Example Modify the CAS configuration file

Example Modify the CAS web-INF /cas.properties file

server.name=http://localhost:9100

1.4.2 Removing HTTPS Authentication

The CAS uses the HTTPS protocol by default. If the HTTPS protocol is used, an SSL certificate is required (you must apply for or purchase an SSL certificate from a specific organization). If security requirements are not high or in the development and testing phase, HTTP can be used. We describe how to modify the configuration to enable CAS to use HTTP.

  1. Modify the cas WEB – INF/deployerConfigContext. XML

Find the configuration below

<bean class=”org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler” p:httpClient-ref=”httpClient”/>

The parameter p:requireSecure=”false” needs to be added. The requireSecure attribute indicates whether security authentication is required, that is, HTTPS. False indicates that security authentication is not required

  1. Modify the cas/WEB – INF/spring – the configuration/ticketGrantingTicketCookieGenerator. XML

Find the following configuration

<bean id=”ticketGrantingTicketCookieGenerator” class=”org.jasig.cas.web.support.CookieRetrievingCookieGenerator”      p:cookieSecure=”true”      p:cookieMaxAge=”-1″      p:cookieName=”CASTGC”      p:cookiePath=”/cas” />

P :cookieSecure=”true”, which is also related to HTTPS authentication. True indicates THAT HTTPS authentication is used, and FALSE indicates that HTTPS authentication is not used.

Parameter P :cookieMaxAge=”-1″, is the maximum life cycle of COOKIE, -1 is no life cycle, that is, only the currently opened window is valid, close or reopen other Windows, will still require verification. You can change the value to a number greater than 0 as required, such as 3600, which means that any window is opened within 3600 seconds without verification.

We’ll change cookieSecure to false and cookieMaxAge to 3600

(3) modify the cas WEB – INF/spring – the configuration/warnCookieGenerator. XML

Find the following configuration

<bean id=”warnCookieGenerator” class=”org.jasig.cas.web.support.CookieRetrievingCookieGenerator” p:cookieSecure=”true” p:cookieMaxAge=”-1″ p:cookieName=”CASPRIVACY” p:cookiePath=”/cas” />

We’ll change cookieSecure to false and cookieMaxAge to 3600

1.5 CAS Client Start Demo

1.5.1 Client Project 1 Construction

(1) Dependency is introduced into the construction project

Create the Maven project (WAR) casclient_demo1 Import the CAS client dependency and set the Tomcat running port to 9001

<dependencies><! —cas –>  <dependency>      <groupId>org.jasig.cas.client</groupId>      <artifactId>cas– the client – core < / artifactId > < version > 3.3.3 < / version > < / dependency > <dependency><groupId>javax.servlet</groupId><artifactId>servletapi</artifactId><version>2.5</version>  <scope>provided</scope></dependency></dependencies>    <build>    <plugins>      <plugin>            <groupId>org.apache.maven.plugins</groupId>            <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> < Configuration > <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-mavenplugin</artifactId><configuration><! — Specify a port –><port>9001</port><! – request path – > < path > / < / path > < / configuration > < / plugin > < / plugins > < / build >

(2) Add web.xml

<? xml version= *“1.0” * encoding= *“UTF-8”*? ><web-app xmlns:xsi= **”www.w3.org/2001/XMLSch… **”http://java.sun.com/xml/ns/javaee”**xsi:schemaLocation= **”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”**version= *“2.5”* > <! — For single signout, this filter is used for single signout, Optional configuration – > < listener > < listener – class > org). Jasig cas. The client. The session. SingleSignOutHttpSessionListener < / listener – class > </listener> <! This filter is optional for single sign-off. –> <filter> <filter-name>CAS Single Sign Out Filter</filter-name> <filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class> </filter> <filter-mapping> <filter-name>CAS Single Sign Out Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! — The filter is responsible for user authentication, It must be enabled –> <filter> <filter-name>CASFilter</filter-name> <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class> <init-param> <param-name>casServerLoginUrl</param-name> <param-value>http://localhost:9100/cas/login</param-value> <! </init-param> <param-name>serverName</param-name> <param-value>http://localhost:9001</param-value> </init-param> </filter> <filter-mapping> <filter-name>CASFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! — This filter is responsible for Ticket verification. It must be enabled –> <filter> <filter-name>CAS Validation filter </filter-name> <filter-class> org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter</filter-class> <init-param> <param-name>casServerUrlPrefix</param-name> <param-value>http://localhost:9100/cas</param-value> </init-param> <init-param> <param-name>serverName</param-name> <param-value>http://localhost:9001</param-value> </init-param> </filter> <filter-mapping> <filter-name>CAS Validation Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! This filter is responsible for implementing the package of HttpServletRequest requests, such as allowing the developer to obtain the SSO login user’s login name via the getRemoteUser() method of HttpServletRequest, optionally configured. –> <filter> <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name> <filter-class> org.jasig.cas.client.util.HttpServletRequestWrapperFilter</filter-class> </filter> <filter-mapping> <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! — through the filter allows developers to org.. Jasig cas. Client. Util. AssertionHolder to obtain the user’s login name. Such as AssertionHolder. GetAssertion (.) getPrincipal () getName (). –> <filter> <filter-name>CAS Assertion Thread Local Filter</filter-name> <filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilter</filter-class> </filter> <filter-mapping> <filter-name>CAS Assertion Thread Local Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

(3) Write index.jsp

<%@ page language= *“java” * contentType= “text/html; charset=utf-8”    pageEncoding= *“utf-8”* % > <! DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”www.w3.org/TR/html4/lo… *“Content-Type” * content= *“text/html; charset=utf-8”* > < title > yipin optimal purchase < / title > < / head > < body > welcome to swallow optimal purchase < % = request. The getRemoteUser () % > < / body > < / HTML >

Request.getremoteuser () is used to obtain the remote login name

1.5.2 Client Project 2 Construction

(1) Create Maven project (WAR) casclient_demo2 Import the CAS client dependency and set the Tomcat running port to 9002

(2) Create web. XML, refer to casclient_demo1, change the value of serverName to http://localhost:9002

(3) Create index.jsp and display “Welcome to Erpin-youbuy”

1.5.3 Single sign-on Test

  1. Start tomcat for cas deployment
  2. Start client project 1 and client project 2
  3. If you enter http://localhost:9001/ or http://localhost:9002/ in the address box, the CAS login page is displayed
  4. After you enter the user name and password, go to 9002. You can also access 9001 again.

1.5.4 Sso Login

The address bar enter http://localhost:9100/cas/logout

You can see the prompt page after exiting

We can add this link to index.jsp

<a href= “http://localhost:9 1 *00/cas/logout”*> Log out </a>

But we prefer to log out, can automatically jump to a page, so how to deal with?

Example Modify the configuration file cas-servlet.xml of the CAS system

  <bean id=”logoutAction” class=”org.jasig.cas.web.flow.LogoutAction”        p:servicesManager-ref=”servicesManager”        p:followServiceRedirects=”${cas.logout.followServiceRedirects:true}”/>

Changing to true allows you to jump to the target page on exit and modify the exit link for index.jsp

<a href= “http://localhost:9 1 *00/cas/logout? service=http:// *www.baidu.com **> Log out </a>

2. Configure the DATA source on the CAS server

2.1 Requirement Analysis

We now allow the username and password to be authenticated from our User table in YouTube

2.2 Configuring a Data Source

(1) to modify the cas server in the web – under the inf deployerConfigContext. XML, add the following configuration

<bean id=”dataSource” class=”com.mchange.v2.c3p0.ComboPooledDataSource” p:driverClass=”com.mysql.jdbc.Driver” P: jdbcUrl = “JDBC: mysql: / / 127.0.0.1:3306 / pinyougoudb? characterEncoding=utf8″ p:user=”root” p:password=”123456″ /><bean id=”passwordEncoder”class=”org.jasig.cas.authentication.handler.DefaultPasswordEncoder” c:encodingAlgorithm=”MD5″ p:characterEncoding=”UTF-8″ /> <bean id=”dbAuthHandler” class=”org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler” p:dataSource-ref=”dataSource” p:sql=”select password from tb_user where username = ?” p:passwordEncoder-ref=”passwordEncoder”/>

Then locate the following configuration at the beginning of the configuration file

 <bean id=”authenticationManager” class=”org.jasig.cas.authentication.PolicyBasedAuthenticationManager”>        <constructor-arg>            <map>                               <entry key-ref=”proxyAuthenticationHandler” value-ref=”proxyPrincipalResolver” />                <entry key-ref=”primaryAuthenticationHandler” value-ref=”primaryPrincipalResolver” />            </map>        </constructor-arg>              <property name=”authenticationPolicy”>            <bean class=”org.jasig.cas.authentication.AnyAuthenticationPolicy” />        </property></bean>

Among them

 <entry key-ref=”primaryAuthenticationHandler” value-ref=”primaryPrincipalResolver” />

Use a fixed username and password. We can see these two beans below. If we use database authentication for username and password, we need to comment out this sentence.

Add the following configuration

<entry key-ref=”dbAuthHandler” value-ref=”primaryPrincipalResolver”/>

(2) Put the following three JAR packages into webapps\cas\ web-INF \lib

(These jar packages are in the resource \cas\jar directory)

Test with the username and password in the database

3. Modify the CAS server interface

3.1 Requirement Analysis

Now we start to change the default login page of CAS to our own login page

3.2 Makeover

3.2.1 Copying Resources

(1) Copy the login page login. HTML to web-INF \view\ JSP \default\ UI in CAS system

(2) Copy the CSS and JS folders to the CAS directory

(3) Rename the original casloginView.jsp (for reference later) and rename login.html to casLoginView.jsp

3.2.2 Modifying the Page

Edit the casloginview.jsp content

(1) Add instructions

<%@ page pageEncoding=”UTF-8″ %><%@ page contentType=”text/html; charset=UTF-8″ %><%@ taglib prefix=”c” uri=”Java.sun.com/jsp/jstl/co…” %><%@ taglib prefix=”spring” uri=”http://www.springframework.org/tags” %><%@ taglib prefix=”form” uri=”http://www.springframework.org/tags/form” %><%@ taglib prefix=”fn” uri=”http://java.sun.com/jsp/jstl/functions” %>

(2) Modify the form tag

<form:form method=”post” id=”fm1″ commandName=”${commandName}” htmlEscape=”true” class=”sui-form”>…… </form:form>
  1. Modify the user name box
<form:input id=”username” tabindex=”1″accesskey=”${userNameAccessKey}” path=”username” autocomplete=”off” HtmlEscape =”true”placeholder=” email/placeholder/placeholder “class=”span2 input-xfat” />
  1. Change password
<form:password id=”password” tabindex=”2″ path=”password” accesskey=”${passwordAccessKey}” htmlEscape=”true” Autocomplete =”off” placeholder=” please input password “class=”span2 input-xfat” />
  1. Modify login button
<input type=”hidden” name=”lt” value=”${loginTicket}” /><input type=”hidden” name=”execution” value=”${flowExecutionKey}” /><input type=”hidden” name=”_eventId” value=”submit” /><input class=”sui-btn btn-block Btn-xlarge btn-danger” accessKey =” value “type=”submit” />

The modified effect is as follows:

3.3 Error Message

Add an error box to the form

<form:errors path=”*” id=”msg” cssClass=”errors” element=”div” htmlEscape=”false” />

Test: input wrong user name and password, prompt is English. The prompt is in the messages.properties file in the WEB-INF\classes directory

authenticationFailure.AccountNotFoundException=Invalid credentials.authenticationFailure.FailedLoginException=Invalid credentials.

Set it to zn_CN and modify cas-servlet.xml

<bean id=”localeResolver” class=”org.springframework.web.servlet.i18n.CookieLocaleResolver” p:defaultLocale=”zh_CN” />

We need to copy this information to messages_zh_cn.properties and change it to Chinese prompt (transcoding).

authenticationFailure.AccountNotFoundException=\u7528\u6237\u4E0D\u5B58\u5728.authenticationFailure.FailedLoginException =\u5BC6\u7801\u9519\u8BEF.

The first is an error when the user name does not exist

The second is the password error prompt

4. The CAS client is integrated with SpringSecurity

4.1 Spring Security test project construction

(1) Establish Maven project casclient_demo3, introduce spring dependencies and Spring Secrity dependencies, and set the Tomcat port to 9003

(2) Build web. XML, add filters and other configurations

(3) Create the configuration file spring-security.xml

(4) Add HTML pages

Refer to our Spring-security-demo in Chapter 4 for the above steps

4.2 Spring Security is Integrated with CAS

(1) Introducing dependencies

<dependency>     <groupId>org.springframework.security</groupId>     <artifactId>spring-security-cas</artifactId> <version> 4.1.0.release </version> </dependency> <dependency> <groupId>org.jasig.cas.client</groupId> <artifactId>cas-client-core</artifactId> <version>3.3.3</version> <exclusions> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> </exclusion> </exclusions> </dependency>

(2) Modify spring-security.xml

<? xml version= *“1.0” * encoding= “UTF-8” ? ><beans:beans xmlns= **”www.springframework.org/schema/secu…”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.xsdwww.springframework.org/schema/secu… http://www.springframework.org/schema/security/spring-security.xsd”* > <! — entry-point-refEntry point reference –>< HTTP use-expressions= *“false” * entry-point-ref= *“casProcessingFilterEntryPoint” *>          <intercept-url pattern= *“/ * *” * access= *“ROLE_USER” */>           <csrf disabled= *“true”* / > <! — custom filter, position, before, and after –> <custom filter ref= *“casAuthenticationFilter” *  position= *“CAS_FILTER” * />              <custom-filter ref= *“requestSingleLogoutFilter” * before= *“LOGOUT_FILTER” */>          <custom-filter ref= *“singleLogoutFilter” * before= *“CAS_FILTER”*/> </http> <! — CAS entry point start –> <beans:bean id= *“casProcessingFilterEntryPoint” * class= *“org.springframework.security.cas.web.CasAuthenticationEntryPoint”* > <! — Sso server login URL –> <beans:property name= *“loginUrl” * value= *“http://localhost:9100/cas/login” */>          <beans:property name= *“serviceProperties” * ref= *“serviceProperties” */>      </beans:bean>          <beans:bean id= *“serviceProperties” * class= *“org.springframework.security.cas.ServiceProperties”* > <! –service Configures the root address of the project +/login/cas   –>          <beans:property name= *“service” * value= *“http://localhost:9003/login/cas”*/> </beans:bean> <! — CAS entry point ends –> <! –> <beans:bean id= *“casAuthenticationFilter” * class= *“org.springframework.security.cas.web.CasAuthenticationFilter” *>          <beans:property name= *“authenticationManager” * ref= *“authenticationManager”*/> </beans:bean> <! –><authentication-manager alias= *“authenticationManager” *><authentication-provider  ref= *“casAuthenticationProvider”*></authentication-provider></authentication-manager><! –><beans:bean id= *“casAuthenticationProvider” *     class= *“org.springframework.security.cas.authentication.CasAuthenticationProvider” *>          <beans:property name= *“authenticationUserDetailsService” *>              <beans:bean class= *“org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper” *>                  <beans:constructor-arg ref= *“userDetailsService” * />              </beans:bean>          </beans:property>          <beans:property name= *“serviceProperties” * ref= *“serviceProperties”* / > <! –> <beans: Property name= *“ticketValidator” *>              <beans:bean class= *“org.jasig.cas.client.validation.Cas20ServiceTicketValidator” *>                  <beans:constructor-arg index= *“0” * value= *“http://localhost:9100/cas” */>              </beans:bean>          </beans:property>          <beans:property name= *“key” * value= *“an_id_for_this_auth_provider_only”*/> </beans:bean> <! –><beans:bean id= *“userDetailsService” * class= *“cn.itcast.demo.service.UserDetailServiceImpl”* / > <! — Authentication filter end –><! –> <beans:bean id= *“singleLogoutFilter” * class= *“org.jasig.cas.client.session.SingleSignOutFilter” */>              <beans:bean id= *“requestSingleLogoutFilter” * class= *“org.springframework.security.web.authentication.logout.LogoutFilter” *>          <beans:constructor-arg value= *“http://localhost:9100/cas/logout? service=http://www.baidu.com” */>          <beans:constructor-arg>              <beans:bean class= *“org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler” */>          </beans:constructor-arg>          <beans:property name= *“filterProcessesUrl” * value= *“/logout/cas”*/> </beans:bean> <! </beans:beans>

(3) Create UserDetailsServiceImpl

/** * Authentication */public class UserDetailServiceImpl implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String username) throwsUsernameNotFoundException {/ / build character set List < GrantedAuthority > authorities =new *ArrayList()*; authorities.add(new SimpleGrantedAuthority(“ROLE_USER”));return newUser(username, “” , authorities); }}

The main purpose of this class is to get a user name after logging in, and you can query roles or perform some logic based on the user name.

4.3 Obtaining the Login Name

We need to get a login name for back-end logic, so how do we get a user name for single sign-on? In fact, it’s exactly the same way we got the username before, so let’s do a test.

(1) Web.xml adds SpringMVC

  <servlet>   <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! — Specify the loaded configuration file, Load with contextConfigLocation –> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name>   <url-pattern>*.do</url-pattern>  </servlet-mapping>

(2) Create springmvc. XML

<context:component-scan base-package= *“cn.itcast.demo” * /><mvc:annotation-driven />

Create UserController

@RestControllerpublic class UserController {@RequestMapping(“/findLoginUser”)public void  findLoginUser(){String name = SecurityContextHolder.getContext().getAuthentication().getName(); System.out.println(name); }}

The address bar enter http://localhost:9003/findLoginUser.do login name can be seen in the console output.

4.4 Logging Out

Modify the spring ws-security. XML

<beans:bean id= *“requestSingleLogoutFilter” * class= *“org.springframework.security.web.authentication.logout.LogoutFilter” *>          <beans:constructor-arg value= “http://localhost:9 1 00/cas/logout ? service=http://localhost:9003/index2.html * */>          <beans:constructor-arg>              <beans:bean class= *“org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler” */>          </beans:constructor-arg>          <beans:property name= *“filterProcessesUrl” * value= *“/logout/cas” */>  </beans:bean>

Add links to the page

<a href= *“/logout/cas”*> Log out </a>

Create index2.html and make index2.html anonymously accessible

<http pattern= *“/index2.html” * security= *“none” *></http>

 

5. Excellent Purchase User Center

5.1 Requirement Analysis

The user center implements single sign-on.

5.2 Code Implementation

5.2.1 Sso in the user center

  1. Copy the user-centric pages (beginning with home-) to Pinnyougou-user-Web

 

(2) Pom.xml introduces springSecurity, CAS client, and springSecurity CAS integration package dependencies (see casclient_demo3).

(3) Web.xml add the spring-security filter (see casclient_demo3) and set the home page to home-index.html

<welcome-file-list><welcome-file>home-index.html</welcome-file></welcome-file-list>

(4) build UserDetailsServiceImpl. Java (see casclient_demo3)

  1. Add spring-security.xml (see casclient_demo3) and make the following changes

Configure anonymous access to resources

<! — Anonymous access resources –>< HTTP pattern= *“/css/**” * security= *“none” *></http><http pattern= *“/js/**” * security= *“none” *></http><http pattern= *“/image/**” * security= *“none” *></http><http pattern= *“/plugins/**” * security= *“none” *></http><http pattern= *“/register.html” * security= *“none” *></http><http pattern= *“/user/add.do” * security= *“none” *></http><http pattern= *“/user/sendCode.do” * security= *“none” *></http>

Set service address properties

<beans:bean id= *“serviceProperties” * class= *“org.springframework.security.cas.ServiceProperties” *>         <beans:property name= *“service” * value= *“http://localhost: *910 6 */login/cas” */></beans:bean>  

Setting an Authentication Class

<beans:beanid= *“userDetailsService” * class= * *com.pinyougou.user.service.UserDetailServiceImpl ** / >

5.2.2 Displaying the User name

(1) Create loginController.java by pinyougou-user-web

@RestController@RequestMapping(“/login”)public class LoginController {@RequestMapping(“/name”)public Map showName(){String name = SecurityContextHolder.getContext().getAuthentication().getName(); // Get the login accountMap map=new HashMap<>();map *.put(支那“loginName”支那. *name *) *;returnmap; }}

(2) Create loginservice.js

// app.service(‘loginService’,function($HTTP){// Read list data bound to the formthis.showName=function() {return$http.get(‘.. /login/name.do’); }});

Create indexController.js

// app.controller(‘indexController’,function($scope,loginService){$scope.showName=function(){loginService.showName().success(function(response){$scope.loginName=response.loginName; }); }});

(5) Modify home-index. HTML to introduce JS

    <script type= *“text/javascript” * src= *“plugins/angularjs/angular.min.js” *></script><script type= *“text/javascript” * src= *“js/base.js” *></script><script type= *“text/javascript” * src= *“js/service/loginService.js” *></script><script type= *“text/javascript” * src= *“js/controller/indexController.js” *></script>

Command to call the method to query the login name

<body ng-app= *“pinyougou”ng-controller= *“indexController”ng-init= *“showName()”* >

Display user name

 <span class= *“name” *>{{loginName}}</span>

5.2.3 Logging Out

Set the forward address after logging out

<beans:bean id= *“requestSingleLogoutFilter” * class= *“org.springframework.security.web.authentication.logout.LogoutFilter” *>          <beans:constructor-arg value= “http://localhost:9100/cas/logout *? service=http:// *localhost:9103 ** / >… </beans:bean>

After you log out, the homepage of the website is displayed

<span class= *“safe” *> <a href= *“/logout/cas”</a></span>

The appendix A. Spring Security built-in filter table

The alias The Filter class
CHANNEL_FILTER ChannelProcessingFilter
SECURITY_CONTEXT_FILTER SecurityContextPersistenceFilter
CONCURRENT_SESSION_FILTER ConcurrentSessionFilter
LOGOUT_FILTER LogoutFilter
X509_FILTER X509AuthenticationFilter
PRE_AUTH_FILTER A subclass of AstractPreAuthenticatedProcessingFilter
CAS_FILTER CasAuthenticationFilter
FORM_LOGIN_FILTER UsernamePasswordAuthenticationFilter
BASIC_AUTH_FILTER BasicAuthenticationFilter
SERVLET_API_SUPPORT_FILTER SecurityContextHolderAwareRequestFilter
JAAS_API_SUPPORT_FILTER JaasApiIntegrationFilter
REMEMBER_ME_FILTER RememberMeAuthenticationFilter
ANONYMOUS_FILTER AnonymousAuthenticationFilter
SESSION_MANAGEMENT_FILTER SessionManagementFilter
EXCEPTION_TRANSLATION_FILTER ExceptionTranslationFilter
FILTER_SECURITY_INTERCEPTOR FilterSecurityInterceptor
SWITCH_USER_FILTER SwitchUserFilter