Shiro Security Framework Extension Tutorial--How to extend asynchronous (AJAX) Request authentication failure processing

Source: Internet
Author: User

In the previous chapter we learned how to customize our own filter, this is just to lay the groundwork for this chapter; trust us, this group of Shiro users are more concerned about how asynchronous request authentication fails to deal with this problem, and it is true that a large portion of our current project requests are asynchronous, so the problem is unavoidable, I saw a lot of information on the Internet is not fully given the expansion plan, below I put their own treatment scheme to show under, if there is not good, do not cross the province, home without water meters, do not accept courier ...

Directly into the subject, first look at our previous configuration, customize a Roleauthorizationfilter

<!--filter chain configuration--> <bean id= "Shirofilter" class= "Org.apache.shiro.spring.web.ShiroFilterFactoryBean" > < Property Name= "SecurityManager" ref= "SecurityManager"/> <property name= "loginurl" value= "/"/> <property Name= "Successurl" value= "/cms/"/> <property name= "Unauthorizedurl" value= "/"/> <property name= "f Ilters "> <map> <entry key=" role "> <bean class=" Uthorizationfilter "/> </entry> <entry key=" authc "> <bean class="

	. Shiro.filter.SimpleFormAuthenticationFilter "/> </entry> </map> </property> </bean> <!--Permissions resource configuration--> <bean id= "Filterchaindefinitionsservice" class= " "> <property name=" Definitions " > <value>/static/** = anon/admin/user/ = anon/test/** = role[admin]/abc/** = authc </value> </property> </bean> 

public class Roleauthorizationfilter extends Authorizationfilter {public

	boolean isaccessallowed (servletrequest Request, servletresponse response, Object Mappedvalue)
			throws IOException {Subject Subject

		= Getsubject ( request, response);
		String[] Rolesarray = (string[]) Mappedvalue;

		if (Rolesarray = = NULL | | rolesarray.length = = 0) {
			//No roles specified, so nothing to check-allow access.
			return true;

		set<string> roles = Collectionutils.asset (Rolesarray);
		for (String role:roles) {
			if (subject.hasrole) {return
		return false;


Let's take a look at the source, find that it inherits the Authorizationfilter class, and then only rewrite the Isaccessallowed method, and then we want to isaccessallowed to determine if we have permission, There's got to be a way to authenticate failure callback, which is the consistent practice of the framework to verify that our assumption is correct, we open the source of the Authorizationfilter class to see

Public abstract class Authorizationfilter extends Accesscontrolfilter {public authorizationfilter () {}
    Public String Getunauthorizedurl () {return unauthorizedurl;
    } public void Setunauthorizedurl (String unauthorizedurl) {this.unauthorizedurl = Unauthorizedurl; 
        } protected Boolean onaccessdenied (ServletRequest request, servletresponse response) throws IOException {
        Subject Subject = getsubject (request, response);
        if (subject.getprincipal () = = null) {Saverequestandredirecttologin (request, response);
            else {String Unauthorizedurl = Getunauthorizedurl ();
            if (Stringutils.hastext (Unauthorizedurl)) Webutils.issueredirect (Request, response, Unauthorizedurl);
        else Webutils.tohttp (response). Senderror (401);
    return false;
Private String Unauthorizedurl; }

See the source code when I was very happy to be a cheap smile, it is really I think so, we obviously see a method onaccessdenied, authentication failure processing, logic is if the login entity is null to save the request and Jump login page, otherwise jump without permission to configure the page

We began to reinvent this method and rewrite it in our own roleauthorizationfilter.

/** * * 1. Custom Role authentication filter (to satisfy one of the roles is approved) 2. Extended Asynchronous request authentication prompt function; * * * @author Shadow * */public class Roleauthorizationfilter extends Authorizationfilter {protected Boolean Onacce Ssdenied (ServletRequest request, servletresponse response) throws IOException {HttpServletRequest HttpRequest = (HttpS
		ervletrequest) Request;

		HttpServletResponse HttpResponse = (httpservletresponse) response;

		Subject Subject = getsubject (request, response); if (subject.getprincipal () = = null) {if (Com.silvery.utils.WebUtils.isAjax (HttpRequest)) {com.silvery.utils.WebUt
			Ils.sendjson (HttpResponse, jsonutils.tojsonstring (False, "you are not logged in or too long logon time, please login again!"));
			else {saverequestandredirecttologin (request, response); } else {if (Com.silvery.utils.WebUtils.isAjax (HttpRequest)) {Com.silvery.utils.WebUtils.sendJson (HttpResponse
			, Jsonutils.tojsonstring (New Viewresult (False, "you do not have sufficient permissions to perform the operation!")); else {String Unauthorizedurl = Getunauthorizedurl ();
				if (Stringutils.hastext (Unauthorizedurl)) {Webutils.issueredirect (Request, response, Unauthorizedurl);
				else {webutils.tohttp (response). Senderror (401);
	}} return false; public boolean isaccessallowed (ServletRequest request, servletresponse response, Object mappedvalue) throws Ioexcep
		tion {Subject Subject = getsubject (request, response);

		String[] Rolesarray = (string[]) Mappedvalue;
			if (Rolesarray = = NULL | | rolesarray.length = = 0) {//No roles specified, so nothing to check-allow access.
		return true;
		} set<string> roles = Collectionutils.asset (Rolesarray);
			for (String role:roles) {if (Subject.hasrole) {return true;
	return false; }


In fact, the transformation is also very simple, just add a layer of Ajax judgment, as to how to judge Ajax is their own personal way, and some projects like to add a logo parameters, some people like directly with the header inside the X-requested-with parameters, this look at their own needs slightly, I personally like to be AJAX request authentication failure is to return a string of standard JSON format strings, page compatibility processing is also convenient

Below we test how the effect, first write an HTML, configure/test/ is not enough permission request

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en" "Http://" >

HTML finish, run the project, and then do not login system, directly open HTML click on this button, found alert hint {"message": "You have not logged in or too long logon time, please login!", "Success": false, "value": null};

Then log on to the system and click on this button to request a look at the alert prompt {"message": "You do not have sufficient privileges to perform the operation!", "Success": false, "value": null}; Obviously not yet logged in and insufficient Ajax time hints are perfect to appear, and then this chapter I can retire.

Finally, the expansion of the scheme, in fact, all Shiro filter is a unified interface method, you can see that the real filter is inherited the same parent filter, So the other filter can also provide our asynchronous Request branch processing through the inheritance rewrite OnAccessDenied method

Welcome to the Brick ...

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