Maven build Spring Security3.2 project details

Source: Internet
Author: User

Maven build Spring Security3.2 project details
Preface

It was originally intended to be written on SpringMVC + Hibernate in the previous article. It was found that the previous article was integrated together. It was found that the previous article was too long and it was another article, this article mainly uses Maven to build Spring + SpringMVC + Hibernate + Security integration, while Spring + SpringMVC + Hibernate has already been introduced in the previous article. I will not repeat it in this article, it mainly describes SpringSecurity3.2 permission Control Integration establishment, configuration, and usage precautions.

SpringSecurity Api document address: View

1. Add the SpringSecurity dependency package to Maven

We need to introduce three packages in pom. xml: spring-security-core, spring-security-config, and spring-security-taglibs.

 

               
 
 
  
   org.springframework.security
  spring-security-core
  
   ${security.version}
  
 
 
  
   org.springframework.security
  spring-security-config
  
   ${security.version}
  
 
 
  
   org.springframework.security
  spring-security-taglibs
  
   ${security.version}
  
 

 

2. Configure the security Configuration File

Let's create a configuration file (named casually), I'm called spring-security.xml here, I now define several permissions, the permission information table content is as follows:

Where: The permissions to manage users and all users are configured through the security label in jsp, and others are configured through the spring-security.xml file.

First paste the spring-security.xml file, detailed configuration meaning I will make a simple description:

 

 
 
  
   
Spring-security Configuration
  
  
  
    
    
     
    
   
  
 

Here, we have configured static file management, session conversation management, logon management, logout configuration, permission configuration, and custom data table permission authentication configuration.

 

2.1 static file management

We do not need permission interception for css, image, and js.

2.2 session conversation management

Session management max-sessions = 1 is configured with a maximum of one user login, (Add the following in wab. xml :)

 

 
 
  
   
Org. springframework. security. web. session. HttpSessionEventPublisher
  
 

Error-if-maximum-exceeded = true, if a user logs on, the second user cannot log on,

If the value is false, if one user is logged on, the next user will be kicked off.

In session-manager, We can configure the jump url when the session fails, for example, invalid-session-url =/invalidSession. jsp. If the session fails, the refresh will jump to the invalidSession. jsp page.

2.3 logon Management

Use security: form-login to configure logon. login-page is the logon url, and authentication-failure-url is the url when logon fails (the second url may not exist ),

Username-parameter and password-parameter indicate the username and password in the logon form. If no password is specified, the default values are j_password and j_username.

Login-processing-url: the url to jump to the form action upon logon. If this parameter is left blank, the default value is j_spring_security_check.

2.4 logout Management

Use the security: logout label to configure logout. invalidate-session: whether the session fails to be logged out. Logout-success-url: the address to jump to after logging out successfully.

Logout-url: the deregistered url, which defaults to the http://blog.csdn.net/fengshizty/article/details/j_spring_security_logout if not filled

2.5 permission Configuration

Security: intercept-url is the url to intercept permission authentication, pattern is the intercepted regular matching url, access: required permissions, can be a permission group, separated by commas, requires-channel: intercept http or https. If both are intercept, use any.

2.6 configure a custom permission authentication mechanism

Through the permission table information of our database and the custom permission authentication mechanism, we need to implement the UserDetailsService interface to configure the encryption method of user passwords.

Security: password-encoder: Configure password encryption rules.

3. web. xml container configuration

 

         
 
  
   
ContextConfigLocation
  
  
   
Classpath: spring. xml classpath: spring-hibernate.xmlclasspath: spring-security.xml
  
        
 
 
  
   
SpringSecurityFilterChain
  
  
   
Org. springframework. web. filter. DelegatingFilterProxy
  
 
 
  
   
SpringSecurityFilterChain
  
  
   
/*
  
 
 
 
  
   
Org. springframework. security. web. session. HttpSessionEventPublisher
  
 

The loaded spring-security file, the filter intercepted by security, and the security session listener are configured.

4. Customize authentication to implement the UserDetailsService Interface

UserDetailsServiceImpl is as follows:

Package org. andy. work. service. impl; import java. util. hashSet; import java. util. set; import org. andy. work. dao. userDao; import org. andy. work. entity. acctAuthority; import org. andy. work. entity. acctRole; import org. andy. work. entity. acctUser; import org. apache. log4j. logger; import org. springframework. beans. factory. annotation. autowired; import org. springframework. security. core. grantedAuthority; import org. springframework. security. core. authority. simpleGrantedAuthority; import org. springframework. security. core. userdetails. user; import org. springframework. security. core. userdetails. userDetails; import org. springframework. security. core. userdetails. userDetailsService; import org. springframework. security. core. userdetails. usernameNotFoundException;/*** Creation Time: 5:24:44 ** @ author andy * @ version 2.2 *

* Description: UserDetails interface custom authentication for SpringSecurity */public class UserDetailsServiceImpl implements UserDetailsService {private static final Logger LOGGER = Logger. getLogger (UserDetailsServiceImpl. class); // inject the dao layer @ Autowired private UserDao userDao of the query User; @ Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {LOGGER.info (authenticated User: + username ); // query the database to obtain the information of the modified User. AcctUser acctUser = userDao. findByNickName (username); if (null = acctUser) {throw new UsernameNotFoundException (User: + username + does not exist);} Set Authorities = getAuthorities (acctUser); // set unused attributes to true UserDetails userDetails = new User (acctUser. getNickName (), acctUser. getNickPassword (), true, authorities); return userDetails;} // obtain the permissions of all roles of the user private Set GetAuthorities (AcctUser acctUser) {Set AuthoritySet = new HashSet (); // By default, all users have the permission to browse the user authoritySet. add (new SimpleGrantedAuthority (ROLE _ ); // add if (null! = AcctUser. getAcctRoles () & acctUser. getAcctRoles (). size ()> 0) for (AcctRole role: acctUser. getAcctRoles () {if (null! = Role. getAcctAuthorities () & role. getAcctAuthorities (). size ()> 0) for (AcctAuthority authority: role. getAcctAuthorities () {authoritySet. add (new SimpleGrantedAuthority (authority. getPrefixedName () ;}} return authoritySet ;}}


I will not post the involved AcctUser, AcctRole, and AcctAuthority classes. Otherwise, I will provide the source code.

 

5. Security authentication error message

We can get the authentication error through sessionScope. SPRING_SECURITY_LAST_EXCEPTION.message.

6. Security obtains the user name and user information in the session.

Security stores user information in the session, which can be obtained through the following two methods:

6.1 obtain from the background

 

// Obtain the security context SecurityContext securityContext = SecurityContextHolder. getContext (); // obtain the Authentication object authentication Authentication = securityContext. getAuthentication (); // obtain principal Object principal = authentication from the authentication Object. getPrincipal (); String username =; if (principal instanceof UserDetails) {username = (UserDetails) principal ). getUsername ();} else {username = principal. toString ();}

 

6.1 obtain at the front end

 

Introduce the security Label Library first:

<%@taglib prefix=security uri=http://www.springframework.org/security/tags%>

In View:
 

 

7. Foreground tag authorization

You can use the security: authorize label to set permissions. The three attributes are as follows:

IfAnyGranted: only when the current user has one of the specified permissions can the content inside the tag be displayed (equivalent to the "or" relationship)

IfAllGranted: displays the TAG content (equivalent to the relationship between "and") only when the current user has the specified permission)

IfNotGranted: displays the TAG content (equivalent to a "Non" relationship) when you do not have the specified permission)

Naturally, you can use method to restrict http requests (there are eight types of http requests:-GET-DELETE-HEAD-OPTIONS-POST-PUT-PATCH-TRACE ).

8. Background Controller

LoginController

Package org. andy. work. controller; import org. andy. work. entity. acctUser; import org. apache. log4j. logger; import org. springframework. stereotype. controller; import org. springframework. validation. errors; import org. springframework. web. bind. annotation. modelAttribute; import org. springframework. web. bind. annotation. requestMapping; import org. springframework. web. bind. annotation. requestParam;/*** Creation Time: Under 9:23:34 PM ** @ author andy * @ version 2.2 Description: */@ Controller @ RequestMapping (/login) public class LoginController {private static final Logger LOGGER = Logger. getLogger (LoginController. class); @ RequestMapping (/login) public String login (@ ModelAttribute AcctUser acctUser, @ RequestParam (required = false) Boolean logout, Errors errors) {LOGGER.info (login ); if (null! = Logout) {errors. reject (msg, secure logout);} return/login ;}}

UserController class
Package org. andy. work. controller; import java. util. list; import org. andy. work. entity. acctUser; import org. andy. work. service. userService; import org. apache. log4j. logger; import org. springframework. beans. factory. annotation. autowired; import org. springframework. security. core. authentication; import org. springframework. security. core. context. securityContext; import org. springframework. security. core. context. securityContextHolder; import org. springframework. security. core. userdetails. userDetails; import org. springframework. stereotype. controller; import org. springframework. ui. modelMap; import org. springframework. web. bind. annotation. pathVariable; import org. springframework. web. bind. annotation. requestMapping; import org. springframework. web. bind. annotation. responseBody;/*** Creation Time: 11:49:00 * @ author andy * @ version 2.2 * Description: user Controller */@ Controller @ RequestMapping (/user) public class UserController {private static final Logger LOGGER = Logger. getLogger (UserController. class); @ Autowiredprivate UserService userService; @ RequestMapping (/showInfo/{userId}) public String showUserInfo (ModelMap modelMap, @ PathVariable String userId) {LOGGER.info (query User: + userId ); acctUser userInfo = userService. load (userId); modelMap. addAttribute (userInfo, userInfo); return/user/showInfo;} @ RequestMapping (/showInfos) public @ ResponseBody List showUserInfos () {LOGGER.info (query all users ); list userInfos = userService. findAll (); return userInfos;} @ RequestMapping (/main) public String main (ModelMap modelMap) {LOGGER.info (display homepage ); // obtain the user information in the session saved by security in the background // obtain the security context SecurityContext securityContext = SecurityContextHolder. getContext (); // obtain the Authentication object authentication Authentication = securityContext. getAuthentication (); // obtain principal Object principal = authentication from the authentication Object. getPrincipal (); String username =; if (principal instanceof UserDetails) {username = (UserDetails) principal ). getUsername ();} else {username = principal. toString ();} modelMap. addAttribute (username, username); return/user/main;} @ RequestMapping (/manage) public String manage (ModelMap modelMap) {LOGGER.info (display homepage); modelMap. addAttribute (msg, manage); return/user/option;} @ RequestMapping (/save) public String save (ModelMap modelMap) {LOGGER.info (save); modelMap. addAttribute (msg, save); return/user/option;} @ RequestMapping (/update) public String update (ModelMap modelMap) {LOGGER.info (modify); modelMap. addAttribute (msg, update); return/user/option;} @ RequestMapping (/delete) public String delete (ModelMap modelMap) {LOGGER.info (delete); modelMap. addAttribute (msg, delete); return/user/option ;}}

 

9. Front-end

Login. jsp

 

<%@ page language=java contentType=text/html; charset=UTF-8 pageEncoding=UTF-8%><%@taglib prefix=form uri=http://www.springframework.org/tags/form%><%@taglib prefix=spring uri=http://www.springframework.org/tags%><%@taglib prefix=c uri=http://java.sun.com/jsp/jstl/core%><%@taglib prefix=fmt uri=http://java.sun.com/jsp/jstl/fmt%><%String path = request.getContextPath();String basePath = request.getScheme() + ://+ request.getServerName() + : + request.getServerPort()+ path + /;%>
/> $ {SessionScope. SPRING_SECURITY_LAST_EXCEPTION.message}
User:
Password:
Login
Main. jsp
<%@page language=java contentType=text/html; charset=UTF-8 pageEncoding=UTF-8%><%@taglib prefix=form uri=http://www.springframework.org/tags/form%><%@taglib prefix=c uri=http://java.sun.com/jsp/jstl/core%><%@taglib prefix=fmt uri=http://java.sun.com/jsp/jstl/fmt %><%@taglib prefix=security uri=http://www.springframework.org/security/tags%><%String path = request.getContextPath();String basePath = request.getScheme() + ://+ request.getServerName() + : + request.getServerPort()+ path + /;%>
/> Welcome!
Username retrieved from the backend: $ {username}
All users Manage Users Add User modification Department user delete user

 

10. Test

Currently, andy users have the "Browse users" and "add users" permissions.

When the user password is incorrect:

After logging on with the correct password:

 

Click Add User to jump to the page correctly. As follows:

 

 

Click All users. No permission prompt is displayed.

11. Spring security custom authentication error message

First, copy the messages_zh_CN.properties file written by spring-security-core to the src/main/resources Directory of the project.

Modify the corresponding prompt. According to our own requirements, I name it messages. properties.

Next, we need to add the following content to the spring configuration file:

 

 
 

OK. Maven has integrated Spring, Hibernate, and security.

 

 

Follow-up

Legacy problems, General rewrite security prompt information, others can be International Chinese prompt,

Only

ConcurrentSessionControlStrategy. exceededAllowed = {0} users have logged on and cannot log on again

When I modify the duplicate logon prompt, the original security prompt is as follows:

 

I hope to share some comments with you again.

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.