Spring security implements login and permission role control, springsecurity

Source: Internet
Author: User

Spring security implements login and permission role control, springsecurity

Casual Introduction

1. spring version: 4.3.2.RELEASE + spring security version: 4.1.2.RELEASE (others are not described here)
2. All displayed content is configured with annotations.
3. springmvc has been configured. Do not describe it.
4. springmvc, spel, and el will be involved. If you are not familiar with springmvc, you can take a look at this content first, especially springmvc.

First, think about what is required for login. In the simplest case, the user name, password, and then compare the database. If they match, they will jump to the personal page. Otherwise, they will return to the login page and prompt that the user name and password are incorrect. In this process, you should also have a permission role and run through the entire session. With this idea, we only need to hand over the username and password of the database to spring security for comparison, and then let security jump, and let security help us put the permission role and username through the entire session. In fact, we only need to provide the correct user name and password and configure security.

Directory

Preparations
Login Page
Personal page
Start configuring spring security

1. Start spring security

2. Configure permissions

3. Compile UserDetailService

First, prepare the database table.

CREATE TABLE `user` ( `username` varchar(255) NOT NULL, `password` char(255) NOT NULL, `roles` enum('MEMBER','MEMBER,LEADER','SUPER_ADMIN') NOT NULL DEFAULT 'MEMBER', PRIMARY KEY (`username`), KEY `username` (`username`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

PS: note the content of roles. LEADER is also a MEMBER. In this way, LEADER has the permissions of MEMBER. Of course, you can also make a judgment in the application. This will be discussed later.

 Login Page

<% @ Page contentType = "text/html; charset = UTF-8" language = "java" isELIgnored = "false" %> <% @ taglib prefix = "c" uri =" http://java.sun.com/jsp/jstl/core "%> <% @ Taglib prefix =" sf "uri =" http://www.springframework.org/tags/form "%> <Html> 

Personal page

<% @ Page contentType = "text/html; charset = UTF-8" language = "java" isELIgnored = "false" %> <% @ taglib prefix = "security" uri =" http://www.springframework.org/security/tags "%> <% @ Taglib prefix =" sf "uri =" http://www.springframework.org/tags/form "%> <Html> 

Start configuring spring security

1. Start spring security

@Order(2)public class WebSecurityAppInit extends AbstractSecurityWebApplicationInitializer{}

Inheriting AbstractSecurityWebApplicationInitializer, spring security will automatically prepare for the job. Here @ Order (2) is an error occurred when I started springmvc (also pure annotation configuration) and spring security together, I forgot what it is. adding this to enable security to avoid this problem. If there is no error in @ Order (2), you don't have to worry about it.

2. Configure permissions

@ Configuration @ EnableWebSecurity @ ComponentScan ("com. chuanzhi. workspace. service. impl. * ") public class WebSecurityConfig extends websecurityjavaseradapter {@ Autowired private UserDetailService userDetailService; // Add the following if userDetailService is not scanned: @ ComponentScan @ Override protected void configure (HttpSecurity http) throws Exception {http. authorizeRequests (). antMatchers ("/me "). hasAnyRole ("MEMBER", "SUPE R_ADMIN ") // The personal homepage can only be accessed by users with the MENBER and SUPER_ADMIN roles. anyRequest (). authenticated (). and (). formLogin (). loginPage ("/"). permitAll () // here, the default path of the program is the logon page, allowing everyone to log on. loginProcessingUrl ("/log") // processing url submitted for login. failureForwardUrl ("/? Error = true ") // If the logon fails, the system returns to the logon page. The parameter error can indicate the logon status. defaultSuccessUrl ("/me") // The url for successful login. Go to the personal homepage here. and (). logout (). logoutUrl ("/logout "). permitAll (). logoutSuccessUrl ("/? Logout = true ") // in order, the first is the logout url, and security intercepts this url for processing. Therefore, logout is not required, and the second is the logout url, logout informs the login status. and (). rememberMe (). tokenValiditySeconds (604800) // remember me function. The cookie period is one week. rememberMeParameter ("remember-me") // whether to activate the parameter name of the remember me function during login. The parameter name is displayed on the login page. rememberMeCookieName ("workspace"); // cookie name. After logging in, you can view the cookie name in the browser.} @ Override public void configure (WebSecurity web) throws Exception {super. configure (web) ;}@ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth. userDetailsService (userDetailService); // configure custom userDetailService }}

3. Compile UserDetailService

Spring security provides us with services to obtain user information, mainly to provide security with information to verify users. Here we can customize our own needs, this is how I obtain the user information from the database based on the username, and then hand it to security for subsequent processing.

@ Service (value = "userDetailService") public class UserDetailService implements UserDetailsService {@ Autowired private UserRepository repository; public UserDetailService (UserRepository userRepository) {this. repository = userRepository; // User repository, which is not described here} public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {user User = repository. findUserByUsername (username); if (User = null) throw new UsernameNotFoundException ("this account cannot be found! "); // Throw an exception. The logon Failure page is displayed based on the configuration. List <GrantedAuthority> list = new ArrayList <GrantedAuthority> (); // GrantedAuthority is the permission class provided by security, getRoles (user, list); // obtain the role and put it in the list org. springframework. security. core. userdetails. user auth_user = new org. springframework. security. core. userdetails. user (user. getUsername (), user. getPassword (), list); // return the security return auth_user ;} /*** get the role * @ param user * @ param list */public void getRoles (User user, List <GrantedAuthority> list) {for (String role: user. getRoles (). split (",") {list. add (new SimpleGrantedAuthority ("ROLE _" + role); // if the permission prefix is ROLE _, security considers this ROLE information rather than permission, for example, ROLE_MENBER is the MENBER role, and CAN_SEND is the CAN_SEND permission }}}

If you want to jump to the personal homepage next time you enter the logon page to view the Controller code when the "remember me" function is effective

/*** Logon page ** @ param * @ return */@ RequestMapping (value = "/") public String login (Model model, User user, @ RequestParam (value = "error", required = false) boolean error, @ RequestParam (value = "logout", required = false) boolean logout, HttpServletRequest request) {model. addattriication (user); // if you have logged on to the personal homepage, Authentication authentication = SecurityContextHolder. getContext (). getAuthentication (); if (authent Ication! = Null &&! Authentication. getPrincipal (). equals ("anonymousUser") & authentication. isAuthenticated () return "me"; if (error = true) model. addAttribute ("error", error); if (logout = true) model. addAttribute ("logout", logout); return "login ";}

Result Display:

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.