Permission control (coarse particles + fine particles)

Source: Internet
Author: User
Tags log log

1 Coarse granular permission control (complete with filter)

Analysis:

Accurate access control to the session (determine if the session exists)

Use the filter to complete the control of coarse granular permissions, if the session does not exist to jump to the first page, if there is a URL link can be accessed to the corresponding operation.

First step: Define a filter:

Public class Systemfilter implements Filter {

/**web when the container starts, the method of execution */

A connection that needs to be released before the session is stored

list<string> list = new arraylist<string> ();

Public void init (filterconfig config) throws servletexception {

List.add ("/index.jsp");

List.add ("/image.jsp");

List.add ("/system/elecmenuaction_menuhome.do");

}

/** the method of Dofilter the filter is executed each time the URL connection is accessed */

Public void DoFilter (servletrequest req, servletresponse Res,

Filterchain chain) throws IOException, servletexception {

HttpServletRequest request = (httpservletrequest) req;

HttpServletResponse response = (httpservletresponse) res;

Get access to the connection address

String path = Request.getservletpath ();

Get the Name,password value from the cookie before you visit the Homepage index.jsp page and display it on the page (remember me)

this. Forwordindexpage (path,request);

If the path of the access path contains the stored connection of the released list, it needs to be released at this time

if (list.contains (path)) {

Chain.dofilter (request, response);

Return

}

        // gets the user logon Session

Elecuser Elecuser = (elecuser) request.getsession (). getattribute ("Globle_user");

        // Release

if (elecuser!=null) {

Chain.dofilter (request, response);

Return

}

        // REDIRECT to login page

Response.sendredirect (Request.getcontextpath () + "/index.jsp");

}

/** Destruction */

Public void Destroy () {

}

/** get the Name,password value from the cookie and display it on the page (remember me) * * Before visiting the index.jsp page of the homepage.

Private void forwordindexpage (String path, httpservletrequest request) {

if (path!=null && path.equals ("/index.jsp")) {

String name = "";

String password = "";

String checked = "";

Cookies [] cookies = request.getcookies ();

if (cookies!=null && cookies.length>0) {

for (Cookie cookie:cookies) {

if (Cookie.getname (). Equals ("name")) {

Name = Cookie.getvalue ();

/**

* If name appears in Chinese, decode Chinese

*/

Try {

Name = Urldecoder. Decode (Name, "UTF-8");

} catch (Unsupportedencodingexception e) {

E.printstacktrace ();

}

Checked = "Checked";

}

if (Cookie.getname (). Equals ("password")) {

Password = Cookie.getvalue ();

}

}

}

Request.setattribute ("name", name);

Request.setattribute ("password", password);

Request.setattribute ("Checked", checked);

}

}

}

Step two: Add the corresponding filter in the Web container:

<!--custom filters required to be added to the front of the struts2 filter--

<filter>

<filter-name>SystemFilter</filter-name>

<filter-class>cn.itcast.elec.util.SystemFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>SystemFilter</filter-name>

<url-pattern>*.do</url-pattern>

<url-pattern>*. JSP</url-pattern>

</filter-mapping>

Problem: not friendly, access links, it is best to prompt "illegal operation, the system will be 5 seconds after the jump to the login page"

To modify an action in a filter class:

(1) Add 2 release connections to the Init method in the filter:

List.add ("/error.jsp");

List.add ("/system/elecmenuaction_logout.do");

(2) Redirect to error.jsp in the Dofilter method

Will:

Redirect to login page

Response.sendredirect (Request.getcontextpath () + "/index.jsp");

Modified to:

Redirect to Error.jsp (5-Second jump to login page)

Response.sendredirect (Request.getcontextpath () + "/error.jsp");

(3) Contents of error.jsp:

<script>

var i=6;

var T;

function Showtimer () {

if (i==0) {///If the number of seconds is 0, clear T, prevent the call function, for slow-reacting machines may not achieve the effect of jump, so to clear off setinterval ()

parent.location.href= "${pagecontext.request.contextpath}/system/elecmenuaction_logout.do";

Window.clearinterval (t);

}else{

i = i-1;

The number of seconds is reduced and inserted in the timer layer

document.getElementById ("Timer"). Innerhtml= i+ "seconds";

}

}

// call a function every second Showtimer ()

t = window.setinterval (showtimer,1000);

</script>

Note: The session should not be in the server has not been emptied, if too many sessions, will lead to a large session pressure, the system becomes slow, so requires 10 minutes if the operating system, the session will be automatically emptied. configuring in Web. xml

<session-config>

<session-timeout>10</session-timeout>

</session-config>

Coarse granular permission Control for interview:

Using filters

Define the release connection in the filter, because not every operation will have a session

In the filter to get login after the session, if the session is not empty, then release, that can operate the defined business functions, if the session is empty, then jump to the login page.

The system that controls access must be present in the session

2 Fine Grain permission control (interceptors using STRUTS2)

/**
* Custom Annotations
*/
Annotations modified by this annotation, using reflection to read other annotations
@Retention (Retentionpolicy.runtime)
Public @interface Annotationlimit {
String mid ();//code for permission
String pid ();//The Code of the parent permission
}

public class Errorandlimitinterceptor extends Methodfilterinterceptor {

/** Interceptor */
@Override
Protected String dointercept (Actioninvocation actioninvocation) throws Exception {
Put the custom error message in the request
HttpServletRequest request = (httpservletrequest) actioninvocation
. Getinvocationcontext (). get (Strutsstatics.http_request);
try {
Gets the requested action object
Object action = Actioninvocation.getaction ();
Gets the name of the requested method
String methodName = Actioninvocation.getproxy (). GetMethod ();
Gets the wrapper class for the method in the action (the method in action has no parameters)
Method method = Action.getclass (). GetMethod (methodName, NULL);
The return value of the action
String result = null;

Complete granular permission control before completing the jump action, controlling each method of action
URL to check whether permissions can be manipulated by annotations
Boolean flag = Ischecklimit (Request,method);
if (true) {
Run an action that is intercepted, during which case an exception is caught
result = Actioninvocation.invoke ();
}
else{
Request.setattribute ("ErrorMsg", "Sorry! You do not have permission to operate this feature! ");
return "ErrorMsg";
}
return result;
} catch (Exception e) {
/**
* Handling Exceptions
*/
String errormsg = "There is an error message, please check the log!" ";
Judging by instanceof What is the exception type
if (e instanceof runtimeexception) {
Unknown run-time exception
RuntimeException re = (runtimeexception) e;
Re.printstacktrace ();
ErrorMsg = Re.getmessage (). Trim ();
}
/**
* Send error message to page
*/
Request.setattribute ("ErrorMsg", errormsg);

/**
* log4j Log
*/
Log log = Logfactory
. GetLog (Actioninvocation.getaction (). GetClass ());
Log.error (ErrorMsg, E);
return "ErrorMsg";
}//... end of catch
}


/** Verify Fine grain permission control */
public boolean ischecklimit (HttpServletRequest request, method) {
if (method = = null) {
return false;
}
Get the current login user
Elecuser Elecuser = (elecuser) request.getsession (). getattribute ("Globle_user");
if (Elecuser = = null) {
return false;
}

Get the role of the current logged-on user (one user can correspond to multiple roles)
Hashtable<string, string> ht = (Hashtable) request.getsession (). getattribute ("Globle_role");
if (HT = = NULL) {
return false;
}
Process annotations to determine if there are annotations on the method (the name of the note is: annotationlimit)
/*
For example
* @AnnotationLimit (mid= "AA", pid= "0")
Public String Home () {
*/
Boolean isannotationpresent = Method.isannotationpresent (Annotationlimit.class);

There is no annotation (this method cannot be manipulated at this time)
if (!isannotationpresent) {
return false;
}

Presence Annotations (Invoke annotations)
Annotationlimit limit = method.getannotation (Annotationlimit.class);

Get the value on the annotation
String mid = Limit.mid (); Permissions Sub-module name
String pid = Limit.pid (); Permission Parent Action Name

/**
* If login user's role id+ annotation on @annotationlimit (mid= "AA", pid= "0")
* * There are flag=true in the Elec_role_popedom table, at which point the action method can be accessed;
* * There is no flag=false in the Elec_role_popedom table, the action method cannot be accessed at this time;
*/
Boolean flag = false;
The spring container is loaded in the interceptor to obtain the service class, using the service class to query the corresponding user information
Webapplicationcontext WAC = Webapplicationcontextutils.getwebapplicationcontext (Request.getsession (). Getservletcontext ());
Ielecroleservice Elecroleservice = (ielecroleservice) Wac.getbean (ielecroleservice.service_name);
Traverse role ID
if (Ht!=null && ht.size () >0) {
For (iterator<entry<string, string>> ite = Ht.entryset (). Iterator (); Ite.hasnext ();) {
entry<string, string> Entry = Ite.next ();
Get role ID
String Roleid = Entry.getkey ();
Flag = Elecroleservice.findrolepopedombyid (Roleid, Mid, PID);
if (flag) {
Break
}
}
}
return flag;
}

Question: Why do I use Roleid,mid,pid to query the database in Struts2 interceptors, and why not compare the values of mid with the values of mid defined on the annotations from the session?

Answer: It is not safe at this time, if misappropriation of accounts, login system (must have session), that is, you can operate each method of execution. However, due to the loss of data stored in the database changes, the operation of each function will be the first query permissions, so that the query to ensure data security.

Fine-grained permission-controlled interviews:

using Struts2 The Interceptor

Define an annotation (mid and PID), code for permissions code and parent permissions, add annotations to the top of the method in the Action class

Add annotations (mid= "", Pid= "") on the method of each action class to represent the unique identity of the method (that is, the permissions that the method has)

In the Struts2 interceptor, get the role ID from the session, get annotations (mid and PID) on the action class method, and use role Id,mid and PID to query the role permission table to determine whether the current user can manipulate the method.

Permission control (coarse particles + fine particles)

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.