Spring Security Web application entry environment setup, springsecurity

Source: Internet
Author: User

Spring Security Web application entry environment setup, springsecurity

Before using Spring Security to configure Web applications, you must first prepare a Web application created based on the Maven Spring framework (Spring MVC is not mandatory). The content in this article is based on this premise.

Pom. xml add dependency

In addition to some dependency packages of the Spring framework, you also need to add the dependency packages of Spring Security in pom. xml:

<dependency>    <groupId>org.springframework.security</groupId>    <artifactId>spring-security-web</artifactId>    <version>4.0.2.RELEASE</version></dependency><dependency>    <groupId>org.springframework.security</groupId>    <artifactId>spring-security-config</artifactId>    <version>4.0.2.RELEASE</version></dependency>

Getting started environment Configuration

To use Spring Security, configure a filter in web. xml. Note that the filter-name must be "springSecurityFilterChain ":

<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>

You also need to configure the Spring Security configuration file and add the file to Spring Application Context:

<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/sp Ring-security.xsd "> 

You only need to complete the above two configurations, start the server, open any Web application page in a browser, will jump to a login page, This login page is automatically generated by Spring Security.


Enter the wrong username and password on the logon page, and a prompt is displayed. Enter the correct user name and password, and then log on to the Web application page. A simple Spring Security-based Web application has been completed!

Logon page

The default logon page of Spring Security is very simple and generally not used directly. A custom logon page is usually specified:

<Http use-expressions = "false"> <! -- You do not need to control permissions on the logon page --> <intercept-url pattern = "/login. jsp *" access = "IS_AUTHENTICATED_ANONYMOUSLY"/> <! -- The USER permission is required to access all other pages --> <intercept-url pattern = "/**" access = "ROLE_USER"/> <! -- Configure the logon page address login-page and the jump address authentication-failure-url after logon failure --> <form-login-page = '/login. jsp 'authentication-failure-url = '/login. jsp? Error '/> <! -- Logout --> <logout/> 

The login form in the jsp of the custom login page:

<c:url value="/login" var="loginUrl" /><form action="${loginUrl}" method="post">    <c:if test="${param.error != null}">        <p>Invalid username and password.</p>    </c:if>    <c:if test="${param.logout != null}">        <p>You have been logged out.</p>    </c:if>    <p>        <label for="username">Username</label>        <input type="text" id="username" name="username" />    </p>    <p>        <label for="password">Password</label>        <input type="password" id="password" name="password" />    </p>    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />    <button type="submit" class="btn">Log in</button></form>

The address of the logon form submission page is/login, and the method is the POST request. To ensure Security and prevent malicious CSRF attacks, Spring Security needs to verify the content submitted by the hidden field in the form.


Logout
<Logout/> in the configuration file is used to process logout.
The logout button on the page:
<C: url value = "/logout" var = "logoutUrl"/> <form action = "$ {logoutUrl}" method = "post"> <input type = "hidden" name =" $ {_ csrf. parameterName} "value =" $ {_ csrf. token} "/> <input type =" submit "value =" quit "/> </form>

The logout request address/logout. The method is a POST request.
Obtain login user information from the database
The username, password, and ROLE of the login user are all configured in the xml configuration file of Spring Security. In actual use, user information is generally not directly configured in the xml file, it is obtained in other ways, such as databases.
Spring Security provides a convenient way to obtain user information through the database, that is, org. springframework. security. core. userdetails. jdbc. jdbcDaoImpl, Which is org. springframework. security. core. userdetails. an Implementation class of the UserDetailsService interface. You only need to configure the DataSource and SQL statements to obtain user information from the database:
<authentication-manager>    <authentication-provider user-service-ref='userDetailsService' /></authentication-manager><beans:bean id="userDetailsService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">    <beans:property name="dataSource" ref="dataSource"/>    <beans:property name="usersByUsernameQuery" value="select username, password, true from t_user where username = ?" />    <beans:property name="authoritiesByUsernameQuery" value="select username, role from t_user_role where username = ?" /></beans:bean>
The preceding configuration can also be simplified:
<authentication-manager>    <authentication-provider>        <jdbc-user-service data-source-ref="dataSource"            users-by-username-query="select username, password, true from t_user where username = ?"            authorities-by-username-query="select username, role from t_user_role where username = ?" />    </authentication-provider></authentication-manager>

Login User information is obtained through other methods
If the user information is not from a database, you need to implement the loadUserByUsername method of the org. springframework. security. core. userdetails. UserDetailsService interface by yourself. That is, you can obtain the user information by using the User Name:
Public class UserDetailsServiceImpl implements UserDetailsService {@ Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {// you can replace if (username. equals ("xxg") {Collection <GrantedAuthority> auths = new ArrayList <GrantedAuthority> (); SimpleGrantedAuthority authority = new SimpleGrantedAuthority ("ROLE_USER"); auths. add (authority); User user = new User (username, "123456", auths); return user;} else {throw new UsernameNotFoundException ("User does not exist ");}}}

Configure the implementation class in the Spring Security configuration file:
<authentication-manager>    <authentication-provider user-service-ref='userDetailsService' /></authentication-manager><beans:bean id="userDetailsService" class="com.xxg.service.UserDetailsServiceImpl" />

Configure URLs not managed by Spring Security
If some URLs in a Web application do not need to be managed by Spring Security, such as some static files or pages that can be viewed without logon, you can configure security = "none" for these URLs ":

Obtain logon user information

Get User Name:

HttpServletRequest. getRemoteUser (); // Servlet standard, SecurityContextHolder. getContext (). getAuthentication (). getName ();

Get user ROLE:

SecurityContextHolder.getContext().getAuthentication().getAuthorities();

Determine whether a user has a ROLE:

httpServletRequest.isUserInRole("ADMIN");


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.