Spring Security Control permissions

Source: Internet
Author: User

Spring Security Control permissions

1, configuring the filter

To use spring security control permissions in your project, first configure the filter in Web. xml so that we can control each request for this project.

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

2, using namespaces

It can be configured in Applicationcontext.xml or separately using a single security.xml , and we use separate XML to to configure .

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:security= "http://www.springframework.org/ Schema/security "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-3.0.xsd http:/ /www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd "> </beans>

We usually use "security" as the default namespace instead of "beans", which means that we can omit the prefix of all security namespace elements, making the context easier to read

<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-3.0.xsd Http://www.springframework.org/schema/security http://www.springframework.org/schema/security/ Spring-security-3.0.xsd "> </beans:beans>

3, configure authentication to provide interface and user information ( use memory user here )

<global-method-security pre-post-annotations= "Enabled" >

</global-method-security>

<intercept-url pattern= "/**" access= "hasrole (' Role_user ')"/>

<form-login />

<authentication-manager>

<authentication-provider>

<user-service>

<user name= "Rod" password= "Rod"

Authorities= "Role_supervisor, Role_user, Role_teller"/>

</user-service>

</authentication-provider>

</authentication-manager>

<beans:bean id= "Loggerlistener"

class= "Org.springframework.security.authentication.event.LoggerListener"/>

Here the configuration pre-post-annotations= "enabled" can be used in the interface function ( must be declared in the interface )/ page using tags / expressions for permission to judge

    • The following expression requires the user to have a role_supervisor role to invoke

Import org.springframework.security.access.prepost.PreAuthorize;

Import sshdemo.entities.*;

Public interface Iownerservice {

@PreAuthorize ("Hasrole (' Role_supervisor ')")

Public list<owners> getowners ();

}

An expression is based on

The Org.springframework.security.access.expression.SecurityExpressionRoot class provides permission to judge .

    • Alternatively, you can use the authorization tag on the page as follows Sec:authorize requires Role_supervisor or Role_teller to use the link .

<% @taglib prefix= "s" uri= "/struts-tags"%>

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

<sec:authorize access= "Hasanyrole (' role_supervisor ', ' Role_teller ')" >

<a href= "<s:url action= ' listaction '/>" >List</a>

</sec:authorize>

The security:authorize tag declares the following properties:

    • ifallgranted: All roles listed in this tab must be authorized to output the contents of the tag.
    • Ifanygranted: Any of the roles listed in this tab must be authorized to output the contents of the tag.
    • Ifnotgranted: None of the characters listed in this tab is authorized to output the contents of the tag.

Use of label Sec:authorize

The authorize label Judgment Order is: access->url->ifnotgranted->ifallgranted->ifanygranted but their relationship is "with": That is, the contents of the middle of the label will not be displayed to the user as long as any one of the properties is not satisfied, for example:

<sec:authorize ifallgranted= "Role_admin,role_member" ifnotgranted= "Role_super" > meet before display to user </sec:authorize >

The content in the middle of the label is displayed only if the current user has the Admin,member role but does not have super privileges

Satisfy ifallgranted: only need Grantedauths.containsall (requiredauths); return true
Meet ifanygranted: Only need to Grantedauths.retainall (requiredauths); content (two convergence)
Satisfies ifnotgranted: In contrast to any, if there is no intersection

3, use custom landing page

Create login.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>

<%

String path = Request.getcontextpath ();

String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";

%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

<% @taglib prefix= "C" uri= "Http://java.sun.com/jstl/core_rt"%>

<base href= "<%=basePath%>" >

<title>Login</title>

<meta http-equiv= "Pragma" content= "No-cache" >

<meta http-equiv= "Cache-control" content= "No-cache" >

<meta http-equiv= "Expires" content= "0" >

<meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" >

<meta http-equiv= "description" content= "This is my page" >

<body>

<c:if test= "${param.error}" >

<font color= "Red" > Your login attempt is not successful, try

Again.<br/>

<br/>

Reason: <c:out value= "${spring_security_last_exception.message}"/>.

</font>

</c:if>

<form action= "${pagecontext.request.contextpath}/j_spring_security_check" style= "Width:260px;text-align: Center; "Method=" POST ">

<fieldset>

<legend> Login </legend>

Users: <input type= "text" name= "J_username" style= "width:150px;" value= "${sessionscope[" Spring_security_last_ USERNAME ']} "/><br/>

Password: <input type= "password" name= "J_password" style= "width:150px;"/><br/>

<input type= "checkbox" Name= "_spring_security_remember_me"/> Two weeks without landing <br/>

<input type= "Submit" value= "Login"/>

<input type= "reset" value= "reset"/>

</fieldset>

</form>

</body>

Configure the Login interface

...

<form-login login-page= "/login.jsp"

Authentication-failure-url= "/login.jsp?error=true"

Default-target-url= "/"/>

...

4, configuring the exit Operation

Add an exit action to a page

<a href= "J_spring_security_logout" >Logout</a>

Configure Exit Actions

...

<logout logout-success-url= "/login.jsp"/>

...

5, configure Access deny action

Create an Access Denied page

<% @page contenttype= "text/html; CHARSET=GBK "%>

<body>

<div id= "Header" ></div>

<div id= "Content" style= "width:60%" >

<strong>access denied</strong>

</div>

</body>

Configure Access Denied redirection page

...

6, run debugging

Precautions :

1, if combined with Struts2 need to put spring security configuration in front of struts2 to prevent struts2 the corresponding processing interception of the following error :

Q: Why does the There is no action mapped for namespace/and action name J_spring_security_check when you log in?

A: This is because the request sent by the login was intercepted by the Struts2 filter, and in order to try the login request can be handled by Spring Security Normally, it needs to be Spring Security Filters are placed before struts2.

2,Struts in conjunction with Spring Security when using access Denied but did not jump to the corresponding accessdenied.jsp page .

Q:Access Denied but did not jump to the corresponding accessdenied.jsp page .

A: The solution is not yet

Spring Security Control permissions

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.