[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[整理]spring + shiro的大概配置。

上一篇:[转帖]HttpClient 4.5版本设置连接超时时间
下一篇:[备忘]Word,标题一,章节名称,自动编号,怎么去掉前面的数字?

添加日期:2016/3/21 11:01:59 快速返回   返回列表 阅读2429次
(1)Maven的pom里加以下依赖。


<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>1.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>1.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.2.4</version>
</dependency>


最新版可以看看http://mvnrepository.com/artifact/org.apache.shiro/shiro-core/

(2)web.xml里加Filter,加在编码filet之后,有特殊的自己看着办。

<!-- 配置shiro的核心拦截器 -->
<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>


(3)spring的配置文件增加以下内容。

<?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-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!-- Shiro Filter -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="loginUrl" value="/login" />
        <property name="successUrl" value="/main" />
        <property name="unauthorizedUrl" value="/login" />
        <property name="filterChainDefinitions">
            <value>
                /login = anon
                /query = authc
                /user/** = authc
                /** = authc
            </value>
        </property>
    </bean>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myRealm" />
    </bean>

    <bean id="myRealm" class="com.why.service.UserRealm"/>

    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager" />

    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

</beans>


loginUrl :没有登录的用户请求需要登录的页面时自动跳转到登录页面,不是必须的属性,不输入地址的话会自动寻找项目web项目的根目录下的”/login.jsp”页面 
successUrl :登录成功默认跳转页面,不配置则跳转至”/”。如果登陆前点击的一个需要登录的页面,则在登录自动跳转到那个需要登录的页面。不跳转到此。 
unauthorizedUrl :没有权限默认跳转的页面。 
filterChainDefinitions : 就是需要验证的地址的列表,常用的包含anon、authc、perms、roles、user、logout。 
/login = anon 代表后缀为/login的链接不验证 
/** = authc 代表其它后缀的链接都进行登录验证,需登录后才能访问。

-------------------------
anon    org.apache.shiro.web.filter.authc.AnonymousFilter
authc    org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authcBasic    org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
logout    org.apache.shiro.web.filter.authc.LogoutFilter
noSessionCreation    org.apache.shiro.web.filter.session.NoSessionCreationFilter
perms    org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
port    org.apache.shiro.web.filter.authz.PortFilter
rest    org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
roles    org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
ssl    org.apache.shiro.web.filter.authz.SslFilter
user    org.apache.shiro.web.filter.authc.UserFilter 如果要验证才能访问的路径,可以用authc或user。authc必须是验证过的,不能是"remember me",而user可以是"remember me",只要Subject包含principal就行。
-----------------------------------------------------
(4)com.why.service.UserRealm是自己写的类,里面实现验证和授权方法。


package com.why.service;

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;

public class UserRealm extends AuthorizingRealm {

    /**
     * 授权,权限.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection p) {
        String username = (String) p.getPrimaryPrincipal();
        System.out.println(username);

        //自己根据需要改改,添加角色,权限啥的
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole("admin");
        info.addStringPermission("all");
        return info;
    }

    /**
     * 认证,是否可以登录.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken myToken = (UsernamePasswordToken)token;
        
        // 用户名、密码
        String username = myToken.getUsername();
        Object password = myToken.getPassword().toString();

        // 简单判断一下
        if (username.equals("abc") && password.equals("123")) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo("哈哈",
                    "嘎嘎", getName());
            return info;

        }

        // 返回null,就是失败.
        return null;
    }

}



(5)再写个controller。


package com.why.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ShiroController {

    /**
     * 登录页面.
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {
        return "shiro/login";
    }

    /**
     * 表单登录.
     * 
     * @param username
     * @param password
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String doLogin(String username, String password,
            HttpSession session, HttpServletRequest request) {

        // 令牌,估计还有别的类型的令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username,
                password);

        
        try {
            // 里面会调用Realm里的doGetAuthenticationInfo方法进行用户认证
            SecurityUtils.getSubject().login(token);
            
            SecurityUtils.getSubject().isAuthenticated();
            
            
            session.setAttribute("username", username); // 写session什么的
            return "main";
        } catch (AuthenticationException e) {

            // login方法抛异常,表示认证失败
            request.setAttribute("message", "login fail.");
            return "shiro/login";
        }

    }

    /**
     * 退出登录.
     * 
     * @param req
     * @return
     */
    @RequestMapping(value = "logout")
    public String logout(HttpServletRequest req) {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }

}



(6)再写个login页面。


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="java.util.*"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="x-ua-compatible" content="IE=9">
<meta name="renderer" content="webkit">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Login</title>

</head>
<body>
    <form action="${ctx}/login" method="post">
        用户名:<input type="text" size="16" name="username" /><br /> 密码:<input type="text" size="16" name="password" /><br /> <input
            type="submit" value="登录" />
    </form>
</body>
</html>



(7)行了,大概意思就有了。剩下就是自己设计表,弄弄用户、角色、权限这些东西了。
如果想在方法上,用注解,好像得在spring-mvc的配置文件里加东西。
jsp页面也能用标签控制权限啥的。
 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved