Advanced Shiro (a) Shiro integration of SSH login authentication

Copyright Notice: Copyright https://blog.csdn.net/qq_21046965/article/details/90139702 procedures monkey jwang

Foreword

      This chapter explains the steps Shiro integration of SSH

method

1. Concept

Before we talk about Shiro authentication and authorization, then in general we are all carried out under conditions web, so let's talk about Shiro integration of SSH key steps. SSH Here is the code when I will SMS before, part of the integration code that I skipped over. Interested parties can in front of me looking through SSH framework of blog.

Project structure:

2. The key step

1) related to the introduction jar

Because it is spring and integration, we need to configure the jar package, the following is maven configuration.

2) a filter disposed in web.xml shiro

<!-- 配置shiro -->
<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <!--表示bean的生命周期由servlet来管理-->
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

3) New shiro spring configuration file, I gave him the name was applicationContext-shiro.xml

Note: In order to let the spring and configuration files loaded with, spring configuration file from the original applicationContext.xml renamed applicationContext-spring.xml

The web.xml configured on loading spring configuration file is changed as follows:

<!-- 加载Spring配置文件 -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext-*.xml</param-value>
</context-param>

4) placed applicationContext-shiro.xml

4.1, we first need to configure the previously assigned class shiroFilter spring proxy filter in web.xml

<!-- 启用shrio授权注解拦截方式 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <!-- 装配 securityManager -->
    <property name="securityManager" ref="securityManager"/>
    <!-- 当访问需要认证的资源时,如果没有认证,则跳转到该url下。不配置则默认为/login.jsp  -->
    <property name="loginUrl" value="/admin/login/login.jsp"/>
    <!-- 配置认证成功跳转的页面,通常不配置,如果没有配置,则跳转到上一个url -->
    <property name="successUrl" value="/admin/list/welcome.jsp"/>
    <!-- 配置用户没有权限访问时跳转的url -->
    <property name="unauthorizedUrl" value="/admin/list/refuse.jsp"/>
    <!-- 配置shiro的过滤器链 -->
    <property name="filterChainDefinitions">
        <value>
            /admin/login/** = anon
            /admin/list/** = authc
            /** = anon
        </value>
    </property>
</bean>

There is the hardest part of the filter chain appreciated shiro nothing less, which is configured to filter the path name =

shiro filter chain built following:

Filter Name Class
anon org.apache.shiro.web.filter.authc.AnonymousFilter
authc org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authcBasic org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
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
logout org.apache.shiro.web.filter.authc.LogoutFilter

其中,anon表示匿名访问,即无需认证即可访问资源。authc表示需要认证通过后才可以访问资源。

4.2、接着,我们需要配置其他的配置项

<!-- 配置Shiro的SecurityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="realm" ref="userRealm"/>
</bean>
<!-- 配置进行授权和认证的 Realm -->
<bean id="userRealm" class="cn.edu.ccut.realm.UserRealm">
    <property name="credentialsMatcher" ref="md5CredentialsMatcher"/>
</bean>
<!-- 配置凭证匹配器 -->
<bean id="md5CredentialsMatcher" class="org.apache.shiro.authc.credential.Md5CredentialsMatcher">
    <property name="hashIterations" value="2"/>
</bean>

注意:这里显然是使用了自定义的realm,我们需要配置一下这个realm

package cn.edu.ccut.realm;

import cn.edu.ccut.bo.User;
import cn.edu.ccut.service.StudentService;
import org.apache.shiro.authc.*;
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.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @Auther:jwang
 * @Date:2019/5/12
 * @Description:cn.edu.ccut.realm
 * @Version 1.0
 **/
public class UserRealm  extends AuthorizingRealm {

    @Autowired
    private StudentService studentService;

    @Override
    public String getName() {
        return "UserRealm";
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        User user = studentService.getUserInfo(username);
        String password = user == null?"":user.getPassword();
        String password_salt = user == null?"":user.getPassword_salt();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password.toCharArray(), ByteSource.Util.bytes(password_salt), getName());
        return info;
    }
}

注意:这里的用户密码和颜值需要从数据库中进行获取,请读者自行编写相关service业务进行获取,我这里已经获取了!

一般而言,数据库中的用户密码都是加密的,所以我们这样配置是为了以后的需要,当然你也可采用明文密码!

4.3、当然还要配置登录的controller方法

/**
 * 用户登录
 * @param username
 * @param password
 * @return
 */
@RequestMapping("/login")
public String login(String username, String password) {
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    // shiro登陆验证
    Subject currentUser = SecurityUtils.getSubject();
    try {
        currentUser.login(token);
        if(currentUser.isAuthenticated()){
            return "/admin/list/welcome";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "/admin/login/login";
}

这就差不多了。

3.问题验证

1)之前配置了未验证情况下直接访问需要验证才可以访问的路径会自动跳转至登录页,我们来试试看:

示例:项目启动直接访问 http://localhost:8090/admin/list/welcome.jsp

Can be found at unauthenticated, it will jump directly to http: // localhost: 8090 / admin / login / login.jsp

Results: verified by

2) We try to visit http: // localhost: 8090 / admin / list / refuse.jsp

It can be found: As we set the / admin / list / ** = authc configure the filter chain, causing it to automatically jump login page.

Because of its limited target page is accessed, we need to be configured to anon

This time the test again to restart the project, we found that without access to the login!

Note: When configuring the project in the following large-scale, otherwise it will fail! The / ** = anon maximum range, preferably on the following.

Guess you like

Origin blog.csdn.net/qq_21046965/article/details/90139702