Spring Integrated Shiro

Source: Internet
Author: User

Apache Shiro is a secure authentication framework that, compared to spring security, uses a relatively straightforward authentication and authorization approach. The Native-session (that is, the authorization information after the user authentication is kept in its own session) mechanism, so that it can and HttpSession, EJB session Bean Container-based session decoupling, to the client application, It can be used by Flex applications, remote method calls, and so on to configure permission authentication. The vcs-admin example in Exit-web-framework uses this framework, which can be used to refer to the official Help documentation. Here's how to combine with spring, dynamically create filterchaindefinitions, and authentication, authorization, and caching processing.

Core Features: authentication , authorization , encryption , session Management

Execution process:

Application code: application code, programmer-written codes

Subject: Interface, representing the current user, provided by the Shiro framework

SecurityManager: Security Manager, provided by the Shiro Framework

Realm: For manipulating security data (users, permissions, roles, and so on), similar to DAO,theShiro Framework provides that the industry can write itself

    • Apache Shiro combined with spring (login to Shiro app)

First step: introduce the coordinates of Shiro in Pom.xml:

<!--permissions control framework--
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>${shiro.version}</version>
</dependency>

  Step Two: configure the integrated Shiro filter in Web. xml

  <filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

  Step Three: Configure a bean in the Spring container with the sameID and filter name as above

<bean id= "Shirofilter" class= "Org.apache.shiro.spring.web.ShiroFilterFactoryBean" >

<!-- inject a Security Manager Object --

<property name= "SecurityManager" ref= "SecurityManager"/>

<!--

Private String loginurl;

Private String Successurl;

Private String Unauthorizedurl;

-

<property name= "loginurl" value= "/login.html"/>

<property name= "Successurl" value= "/index.html"/>

<property name= "Unauthorizedurl" value= "/unauthorizedurl.html" ></property>

<!--the first type of permissions control:URL blocking for permission control --

<property name= "Filterchaindefinitions" >

<!--

authc: represents A filter provided by the Shiro framework to check whether the current user has completed login (authentication)

If you have completed the login, then release, if not completed login, jump to the login page

Anon: represents a filter provided by the framework that can be accessed anonymously (not logged in)

-

<value>

/login.html = Anon

/js/** = anon

/css/** = anon

/images/** = Anon

/validatecode.jsp* = Anon

/useraction_login.action = Anon

/** = authc

</value>

</property>

</bean>

Fourth Step: Configure the Security Manager

<bean id= "SecurityManager" class= "Org.apache.shiro.web.mgt.DefaultWebSecurityManager" ></bean>

  Section Five Step: Provide Useraction, creating the Login method

Package cn.itcast.bos.web.action;
Import Javax.annotation.Resource;
Import Org.apache.commons.lang3.StringUtils;
Import Org.apache.shiro.SecurityUtils;
Import Org.apache.shiro.authc.AuthenticationToken;
Import Org.apache.shiro.authc.UsernamePasswordToken;
Import Org.apache.shiro.subject.Subject;
Import Org.apache.struts2.ServletActionContext;
Import org.apache.struts2.convention.annotation.Action;
Import org.apache.struts2.convention.annotation.Actions;
Import Org.apache.struts2.convention.annotation.Namespace;
Import Org.apache.struts2.convention.annotation.ParentPackage;
Import Org.apache.struts2.convention.annotation.Result;
Import Org.springframework.context.annotation.Scope;
Import Org.springframework.stereotype.Controller;
Import Cn.itcast.bos.domain.User;
Import Cn.itcast.bos.service.IUserService;
Import Cn.itcast.bos.utils.MD5Utils;
@ParentPackage ("Struts-default")
@Namespace ("/")
@Actions
@Controller
@Scope ("prototype")
public class Useraction extends Baseaction<user> {
@Resource
Private Iuserservice UserService;
Private String Checkcode;
public void Setcheckcode (String checkcode) {
This.checkcode = Checkcode;
}
@Action (value = "Useraction_login", results = {
@Result (name = "Success", location = "/index.jsp", type = "Redirect"),
@Result (name = "Login", location = "/login.jsp", type = "redirect")})
Public String Login () {
String key = (string) servletactioncontext.getrequest (). GetSession (). getattribute ("key");
if (Stringutils.isnotblank (Checkcode) && checkcode.equals (key)) {
Subject Subject = Securityutils.getsubject ();
Authenticationtoken token = new Usernamepasswordtoken (Model.getusername (),
MD5UTILS.MD5 (Model.getpassword ()));
try {
Subject.login (token);
Return "Success";
} catch (Exception e) {
E.printstacktrace ();
return "Login";
}
} else {
return "Login";
}
}
}

Sixth step: Customizing a Realm

Package Cn.itcast.bos.myrealm;
Import org.apache.shiro.authc.AuthenticationException;
Import Org.apache.shiro.authc.AuthenticationInfo;
Import Org.apache.shiro.authc.AuthenticationToken;
Import Org.apache.shiro.authc.SimpleAuthenticationInfo;
Import Org.apache.shiro.authc.UsernamePasswordToken;
Import Org.apache.shiro.authz.AuthorizationInfo;
Import Org.apache.shiro.authz.SimpleAuthorizationInfo;
Import Org.apache.shiro.realm.AuthorizingRealm;
Import org.apache.shiro.subject.PrincipalCollection;
Import org.springframework.beans.factory.annotation.Autowired;

Import Cn.itcast.bos.domain.User;
Import Cn.itcast.bos.service.IUserService;

public class Myrealm extends Authorizingrealm {

@Autowired
Private Iuserservice UserService;

@Override
Protected Authorizationinfo Dogetauthorizationinfo (PrincipalCollection paramprincipalcollection) {
TODO auto-generated Method Stub
Simpleauthorizationinfo sai = new Simpleauthorizationinfo ();
Sai.addstringpermission ("Courier");
return sai;
}

/*
* Certification
*/
@Override
Protected AuthenticationInfo Dogetauthenticationinfo (Authenticationtoken paramauthenticationtoken)
Throws Authenticationexception {
Usernamepasswordtoken token = (usernamepasswordtoken) Paramauthenticationtoken;
String username = token.getusername ();
User US = userservice.findbyusername (username);
if (null! = us) {
return new Simpleauthenticationinfo (US, Us.getpassword (), This.getname ());
}
return null;
}

}

provide Userdao Interface:

Package Cn.itcast.bos.dao;

Import Org.springframework.data.jpa.repository.JpaRepository;
Import Org.springframework.data.jpa.repository.JpaSpecificationExecutor;

Import Cn.itcast.bos.domain.User;
Public interface Userrepository extends Jparepository<user, integer>, jpaspecificationexecutor<user>{

User Findbyusername (String username);

}

Step Seventh Configure the spring configuration file

<!--register Security Manager--
<bean id= "SecurityManager" class= "Org.apache.shiro.web.mgt.DefaultWebSecurityManager" >
<property name= "Realm" ref= "Bosloginrealm"/>
</bean>
<!--Configure Custom Realm--
<bean id= "Bosloginrealm" class= "Cn.itcast.bos.myrealm.MyRealm"/>

Spring Integrated Shiro

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.