Ssh+spring Security construction Method and example of "Java EE"

Source: Internet
Author: User
Tags md5 encryption

So far, the basic framework of SSH has been built, and now, on top of that, with the authority control, which is the spring security framework, as in the previous order, first see which libraries need to be added.

1. Pom.xml

Spring security only needs to add its own library to define the properties of a version:

<Properties>    <spring.version>4.0.4.RELEASE</spring.version>    <hibernate.version>4.3.5.Final</hibernate.version>    <spring-security.version>3.2.4.RELEASE</spring-security.version></Properties>

Then add the Spring-security package:

<Dependency>    <groupId>Org.springframework.security</groupId>    <Artifactid>Spring-security-config</Artifactid>    <version>${spring-security.version}</version></Dependency><Dependency>    <groupId>Org.springframework.security</groupId>    <Artifactid>Spring-security-taglibs</Artifactid>    <version>${spring-security.version}</version></Dependency>

Of course there are the necessary packages such as Spring-security-core and Spring-security-web, but they will be imported as dependencies.

2. Web. xml

Spring security is controlled as a filter, so configure this filter in Web. xml:

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

Other things are managed by the spring framework, where spring security is configured and Hibernate is configured, Can be added to the Applicationcontext.xml, but hibernate will have to make a separate infrastructure.xml,security also write a configuration file, called Applicationcontext-security.xml, because this The name is very similar to the front and can be combined to configure contextconfiglocation:

 <  context-param  >  <  param-name  >  contextconfiglocation</  Param-name  >  <  param-value  >  classpath*:/meta-inf /applicationcontext*.xml, classpath:/meta-inf/infrastructure.xml  </< /span>param-value  >  </ context-param  >  

Classpath The following * represents multiple files, followed by a wildcard character, so all XML files starting with/meta-inf/under all ApplicationContext will be read.

3. User.java/role.java

Let's first look at what data tables you need, first create a permission class Role (Org.zhangfc.demo4ssh.domain.Role): Applicationcontext-security.xml.

@Entity
@Table Public classRoleImplementsSerializable {Private Static Final LongSerialversionuid = -7425304725239042741l; Private intID; PrivateString role; @Id Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString Getrole () {returnrole; } Public voidSetrole (String role) { This. Role =role; }}

The Permissions table has two fields, an ID and a permission name, and then modifies the user table:

@Entity
@Table Public classUserImplementsSerializable {Private Static Final LongSerialversionuid = 172643386440351811L; Private intID; PrivateString username; PrivateString password; Privaterole role; @Id @GeneratedValue Public intgetId () {returnID; }@Size (min=6) PublicString GetUserName () {returnusername; } PublicString GetPassword () {returnpassword; }@ManyToOne PublicRole Getrole () {returnrole; } //setter method of Id/username/password/role
}

To save space, I deleted all setter methods, there were two additions, an ID, and a many-to-one foreign key pointing to the role table. Put properties/ Hibernate.properties in the Hibernate.hbm2dll.auto property set to update, and the HomeController home method into the new user's code comment out or delete, first run the program, let the program create a role table and update us Er table, and then edit the data table (I used the navicat), add the following two records to the role table:

After modifying the user table, the previous data is not emptied, but the new two empty fields are added:

This will have two login accounts, the following to write a configuration file.

4. Applicationcontext-security.xml

Put all the configuration on first and then explain.

<Beans:beansxmlns= "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/sprin G-beans-3.2.xsd http://www.springframework.org/schema/security HTTP://WWW.SP Ringframework.org/schema/security/spring-security-3.2.xsd ">     <httpAuto-config= "true">        <Intercept-urlpattern= "/json**"Access= "Role_admin,role_user" />        <Intercept-urlpattern= "/admin**"Access= "Role_admin" />        <Form-loginLogin-page="/"Default-target-url="/"Authentication-failure-url= "/?login=error" />                    <LogoutLogout-success-url="/" />    </http>     <Authentication-manager>        <Authentication-provider>            <!--<password-encoder hash= "MD5" > <salt-source user-property= "email"/> </passwo Rd-encoder> -            <Jdbc-user-serviceData-source-ref= "DataSource"Users-by-username-query= "Select username, password, 1 from user where username =?"Authorities-by-username-query= "Select U.username, r.role from the user U left join role R on U.role_id=r.id where username =?"             />        </Authentication-provider>    </Authentication-manager>    </Beans:beans>

First look at this authentication-manager, this is an authentication manager, the user name password authentication is it to dry, Spring security has a set of default rules, personally think there is not much need to change this default rule, that is, the root directory/j_ Spring_security_check's network request, will be as a login request, and get j_username and J_password as parameters to the user name password matching, this time spring will give j_username to a provider, The task of this provider is to return an object that contains the user name, password, permission (which can be an array), based on the user name. In this place, I used spring Security's own authentication-provider, referencing the data source of the configuration that was previously configured for Hibernate, and executing two SQL statements to query the password based on the user name, Whether the current user is enable and that user right.

After the successful login, all network requests, according to the current user's role to go to the front of the Intercept-url to match (JSON and admin after the two * *, the first representative of the wildcard path, the second representative through the Gamete directory), if the current user's permissions are Role_user , but there is no role_user or is_authenticated_anonymously in the access domain for the URL (which means that anonymous access is allowed), then you cannot access it, and then jump to the login-page set below to let the user log in, of course, Login success before all requests will also go through this chain, so do not put the login interface to set what access rights, or Die loop, log in if successful will jump to Default-target-url set address, if login failed, Will jump to Authentication-failure-url, and now I am set to jump back to the root directory, no matter what.

If it is logout, there is also a default rule, that is, access to the root directory of J_spring_security_logout, the page will jump to Logout-success-url after logout.

5. index.jsp

We access the root directory to access HomeController's home method, and then go to index.jsp, so edit pages/index.jsp (pages is the Web-inf sibling), plus the login form:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%><%@ taglib prefix=" C "uri=" Http://java.sun.com/jsp/jstl/core "%><% @ taglib prefix= "SEC" uri= "http://www.springframework.org/security/tags"%><c:set var= "base" value= "${ PageContext.request.contextPath}/"scope=" session "/><sec:authentication property=" principal "var=" auth " Scope= "Session"/>    User name:<input type= "text" Name= "j_ Username "/><br/>     Password:<input type=" password "name=" J_password "/><br/>    < Input type= "submit" value= "Login"/></form><a href= "${base}j_spring_security_logout" > Logout </a></ Body>

To run the program, access the project root directory:

I used security tags in index.jsp to get an object called Principal, which is a string when not logged in, I print it out, and I can see that the value is "Anonymoususer". Logged in is a user object (not the domain that we define ourselves.) User, but one of spring's Userdetails objects), which will be seen after login.

Log in with zhangsan/123456, click to see, the original printing anonymoususer the place into an object description:

true true true true; Granted Authorities:role_admin

At this time if the index.jsp in the ${auth} changed to ${auth.username} can be printed out Zhangsan. Next visit: Http://localhost:8080/demo4ssh-security/json and http://localhost:8080/demo4ssh-security/admin are all properly accessible, Because Zhangsan is a role_admin, both directories have access rights, but, according to the previous configuration Role_user is not able to access the ADMIN, the following again into the root directory, click Log off after logging in with wangwu/234567 (after logging out if it is printed ${ Auth.username} will throw an exception, because auth this object does not username this domain), after logging in to find that Http://localhost:8080/demo4ssh-security/json can still be accessed normally, HTTP ://localhost:8080/demo4ssh-security/admin but not accessible:

Spring Security Basic configuration is this, compared to the previous several, Spring security such basic configuration is not much use, now who can still use the plaintext password, MD5 encryption in the way of salt is good configuration (I write by email as salt, But for the sake of simplicity, I have no email in the user table of this demo, so I need to pay attention when using MD5. There is a applicationcontext-security.xml I commented out of the configuration is to do this, but, more password storage than this is more complicated, and, without access to return to such an interface, or that sentence, I just want to use the simplest way to build a framework, as for these Details, as long as the basic framework can run is a small thing, these questions will be left to write later.

SOURCE download

Ssh+spring Security construction Method and example of "Java EE"

Related Article

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.