shiro安全认证框架

1.shiro认证:创建SecurityManager-主体提交认证请求-SecurityManager认证-Authenticator认证-realm验证。

package com.dome.com.shiro;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
//自定义realm
public class ShiroRelam extends AuthorizingRealm{
	//存放user的map集合
	Map<String, String> userMap=new HashMap<String, String>();
	{
		userMap.put("make", "f19b50d5e3433e65e6879d0e66632664");
	}
	//权限
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		//从主体中传过来的认证信息中获取用户名
		String userName=(String) arg0.getPrimaryPrincipal();
		//通过数据库获取角色和权限信息
		Set<String> role=getRoleByUserName(userName);
		Set<String> permissions=getPermissionsByUserName(userName);
		SimpleAuthorizationInfo inFo=new SimpleAuthorizationInfo();
		inFo.setRoles(role);
		inFo.setStringPermissions(permissions);
		return inFo;
	}
	//获取权限信息
	private Set<String> getPermissionsByUserName(String userName) {
		Set<String> set=new HashSet<String>();
		set.add("user:delete");
		set.add("user:add");
		set.add("admin:find");
		set.add("admin:update");
		return set;
	}
	//获取角色信息
	private Set<String> getRoleByUserName(String userName) {
		Set<String> set=new HashSet<String>();
		set.add("admin");
		set.add("user");
		return set;
	}
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		// 从主体中传过来的认证信息中,获取用户名
		String userName=(String) arg0.getPrincipal();
		//通过用户名到数据库中获取凭证
		String password=getPassword(userName);
		if(password==null) {
			return null;
		}
		SimpleAuthenticationInfo inFo=new SimpleAuthenticationInfo("make",
				password,"123456");
		
		//加盐
		inFo.setCredentialsSalt(ByteSource.Util.bytes("tom"));
		return inFo;
	}
	//假设是通过数据库来取值通过userName
	private String getPassword(String userName) {
		return userMap.get(userName);
	}
	public static void main(String[] args) {
		Md5Hash md5=new Md5Hash("123456","tom");//加盐一般用随机数这里我们写死tom
		System.out.println(md5.toString());
	}
}

执行

package com.dome.com.testShiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

import com.dome.com.shiro.ShiroRelam;

public class TestShiroRelam {
	@Test
	public void TestAuthentication() {
		//创建自定义的relam对象
		ShiroRelam shiroRelam=new ShiroRelam();
		//构建securitymanager的环境
		DefaultSecurityManager defaultSercurityManager=new DefaultSecurityManager();
		//把自定义的relam设置到securityManage环境中;
		defaultSercurityManager.setRealm(shiroRelam);
		
		//加密
		HashedCredentialsMatcher matcher=new HashedCredentialsMatcher();
		//设置加密名称。
		matcher.setHashAlgorithmName("md5");
		//设置加密次数
		matcher.setHashIterations(1);
		//自定义relam设置CredentialsMatcher
		shiroRelam.setCredentialsMatcher(matcher);
		
		
		//主提交认证请求
		SecurityUtils.setSecurityManager(defaultSercurityManager);
		Subject subject=SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken("make","123456");
		subject.login(token);
		System.out.println("是否认证:"+subject.isAuthenticated());
		//加密加盐不用授权
		/*subject.checkRole("admin");
		subject.checkRole("user");
		subject.checkPermissions("user:delete","user:add");
		subject.checkPermissions("admin:find","admin:update");*/
	}
}

shiro整合spring

pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.dome</groupId>
  <artifactId>shiro_web</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>shiro_web</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  	<!-- spring包 -->
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context</artifactId>
  		<version>4.2.4.RELEASE</version>
  	</dependency>
  	<!-- springmvc -->
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-webmvc</artifactId>
  		<version>4.2.4.RELEASE</version>
  	</dependency>
  	<!-- shiro -->
  	<dependency>
  		<groupId>org.apache.shiro</groupId>
  		<artifactId>shiro-core</artifactId>
  		<version>1.4.0</version>
  	</dependency>
  	<!-- shiro和spring -->
  	<dependency>
  		<groupId>org.apache.shiro</groupId>
  		<artifactId>shiro-spring</artifactId>
  		<version>1.4.0</version>
  	</dependency>
  	<!-- shiroweb -->
  	<dependency>
  		<groupId>org.apache.shiro</groupId>
  		<artifactId>shiro-web</artifactId>
  		<version>1.4.0</version>
  	</dependency>
  	<!-- oracle -->
  	<dependency>  
   		<groupId>com.oracle</groupId>  
   		<artifactId>ojdbc6</artifactId>  
   		<version>11.2.0.1.0</version>  
	</dependency> 
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-jdbc</artifactId>
  		<version>4.2.4.RELEASE</version>
  	</dependency>
    
  </dependencies>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
      
    <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>
	
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
	
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>

    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 注册spring提供的针对POST请求的中文乱码问题 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping> 
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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.xsd">
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="login.html"/>
        <property name="unauthorizedUrl" value="403.html"/>
        <property name="filterChainDefinitions">
            <value>
                /login.html = anon
                /subLogin = anon
                /* = authc
            </value>
        </property>
    </bean>
    <!--创建SecurityMananger对象-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--设置自定义Realm-->
        <property name="realm" ref="realm"/>
    </bean>

    <!--定义自定义的Realm-->
    <bean id="realm" class="com.shiro.relam.ShiroRelam">
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
    </bean>

    <!--设置加密的算法-->
    <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"
          id="credentialsMatcher">
        <property name="hashAlgorithmName" value="md5"/>
        <property name="hashIterations" value="1"/>
    </bean>
</beans>

springMVC.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
        <context:component-scan base-package="com.shiro.controller"/>
        <mvc:annotation-driven/>
        <!--排除静态文件-->
        <mvc:resources mapping="/*" location="/"/>
</beans>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值