shiro learning (IV. shiro integrates spring+springmvc)

Keywords: Java Spring Shiro xml Apache

 

Dependency: Spring context, spring MVC, Shiro core, Shiro spring, Shiro Web

To be honest: web.xml,spring,springmvc configuration files are very difficult

General effect

 

 

Code structure (built with web skeleton)

 

 pom.xml

<dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.4.0</version>
        </dependency>
    </dependencies>

Entity class User

public class User {
    private int id;
    private String username;
    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Custom Realm domain class (salting)

public class CustomRealm extends AuthorizingRealm {    
  @Override
//To grant authorization protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String username = (String) principals.getPrimaryPrincipal(); //By user name username,Getting roles Set<String> roles=getRolesByUsername(username); //By user name username,Getting roles de Jurisdiction Set<String> permissions=getPermissionsByUsrname(username); //Return AuthorizationInfo Object, create first SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(); //Set authorization ---role info.setRoles(roles); //Set authorization ---Jurisdiction info.setStringPermissions(permissions); return info; } private Set<String> getPermissionsByUsrname(String username) { //It's also from the database. It's dead here Set<String> permissions=new HashSet<>(); permissions.add("user:select"); permissions.add("user:update"); permissions.add("user:delete"); permissions.add("user:insert"); return permissions; } private Set<String> getRolesByUsername(String username) { //It's also from the database. It's dead here Set<String> roles=new HashSet<>(); roles.add("admin"); roles.add("user"); return roles; } @Override //Authentication protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String username = (String) token.getPrincipal(); System.out.println("User name:"+username); String pwd=getPwdByUsername(username); System.out.println("Password:"+pwd); if (pwd==null){ return null; } SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(username,pwd,"customRealmSecret");
     info.setCredentialsSalt(ByteSource.Util.bytes(
"salt")); return info; } private String getPwdByUsername(String username) { Map<String,String> map=new HashMap<>(); //Encrypted password admin Salt addition --->c657540d5b315892f950ff30e1394480 map.put("admin","c657540d5b315892f950ff30e1394480"); super.setName("customRealmSecret"); return map.get(username); } }

controller

@Controller
public class UserController {
    @ResponseBody
    @RequestMapping(value = "/subLogin",method = RequestMethod.POST,produces="application/json;charset=utf-8")
    public String subLogin(User user){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());

        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return e.getMessage();
        }
        return "Login successfully";
    }
}

login.htnl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>shiro Login page</title>
</head>
<body>
    <form action="subLogin" method="post">
        <input type="text" name="username"/><br/>
        <input type="password" name="password"/><br/>
        <input type="submit" value="Sign in"/>
    </form>
</body>
</html>

Play: Profile

web.xml

 

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring/spring.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>

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

  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
  <servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:spring/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- Map all requests to the DispatcherServlet for handling -->
  <servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-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"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.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"/>
        <!--Filter page-->
        <property name="filterChainDefinitions">
            <value>
                /subLogin=anon          <!--Submit signed in url No certification required-->
                /login.html=anon         <!--No authentication required, but also accessible-->
                /*=authc                <!--Authentication required to access-->
            </value>
        </property>
    </bean>

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

    <bean class="com.imooc.shiro.realm.CustomRealm" id="realm">
        <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.xsd">



<context:component-scan base-package="com.imooc.controller"/>
    <mvc:annotation-driven/>
    <!--Exclude static files-->
    <mvc:resources mapping="/*" location="/"/>

</beans>

Personal summary:

It's hard to configure, especially if there's a pit in the spring bean. It's web-based

  <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
And I don't have a web
  <bean id="securityManager" class="org.apache.shiro.mgt.DefaultWebSecurityManager">
Oh, that's what happened. I bought a watch for the first night
And then there's, understand, shiro's
shiroFilter,
DefaultWebSecurityManager,
CustomRealm,
HashedCredentialsMatcher (encryption),
It's seven, eight, eight

Posted by php1999 on Tue, 19 Nov 2019 10:12:33 -0800