spring boot 2 + shiro simple authentication examples

Shiro is a powerful and easy to use Java security framework, the official website: https: //shiro.apache.org/.

The main functions of authentication, authorization, encryption and session management.
Other features are Web support, caching, test support, allows a user to access another user's identity with, remember me.

Shiro has three core components: Subject, SecurityManager and Realm.

Subject : namely the current operation "user", "user" does not only refer to people, it can also be a third-party process, the background accounts or other similar things.
SecurityManager : core security manager, Shiro frame by SecurityManager to manage all Subject, and through it to provide a variety of services security management.
Realm : field, acting as a "bridge" or "connector" between Shiro and application security data. That is, when a user performs an authentication (login) and authorization (access control) verification, Shiro looks for information from users and their privileges in the application configuration Realm. When configuring Shiro, you must specify at least a Realm, for authentication, and (or) authorization.

Spring Boot integrin Shiro, introduced in accordance with dependencies shiro-spring and shiro-spring-boot-web- starter different two different methods (Current version is 1.4.2).

Method a: introducing dependencies shiro-spring

1. Create a new project in IDEA SpringBoot, pom.xml cited dependencies are as follows:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.2</version>
        </dependency>
        

2, create and configure the Realm shiro

(1) Create a Realm

Package Penalty for com.example.demo.config; 

Import org.apache.shiro.authc *. ;
 Import org.apache.shiro.authz.AuthorizationInfo;
 Import org.apache.shiro.realm.AuthorizingRealm;
 Import org.apache.shiro.subject .PrincipalCollection; 

public  class myrealm the extends AuthorizingRealm { 

    / ** right information, they will not achieve * / 
    @Override 
    protected AuthorizationInfo doGetAuthorizationInfo (principalCollection principalCollection) {
         return  null ; 
    } 

    / ** authentication: that validate user input account number and password are correct . * / 
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException {
         // get account user input 
        String userName = (String) token.getPrincipal ();
         // verify user admin and password 123456 is correct 
        IF ( "admin"! .equals (userName) ) {
             the throw  new new UnknownAccountException ( "account does not exist!" ); 
        } 
        SimpleAuthenticationInfo authenticationInfo = new new SimpleAuthenticationInfo (the userName, "123456" , getName ());
         return authenticationInfo;
         //Actual project above the user account acquisition objects from the database, and then determines whether there is 
        / * the User User userService.findByUserName = (the userName); 
        IF (User == null) { 
            the throw new new UnknownAccountException ( "account does not exist!"); 
        } 
        = new new SimpleAuthenticationInfo authenticationInfo SimpleAuthenticationInfo (User, user.getPassword (), getName ()); 
        return authenticationInfo; 
        * / 
    } 
}

(2) placed Shiro

package com.example.demo.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    MyRealm myRealm() {
        return new MyRealm();
    }

    @Bean
    DefaultWebSecurityManager securityManager() {
        Manager DefaultWebSecurityManager = new newDefaultWebSecurityManager (); 
        manager.setRealm (myrealm ()); 
        return Manager; 
    } 

    @Bean 
    ShiroFilterFactoryBean shiroFilterFactoryBean () { 
        ShiroFilterFactoryBean the bean = new new ShiroFilterFactoryBean (); 
        bean.setSecurityManager (securityManager ()); 
        // if not the default setting will automatically search "/login.jsp" under the root directory of the Web project page 
        bean.setLoginUrl ( "/ the Login" );
         // login after a successful jump to the link 
        bean.setSuccessUrl ( "/ index" );
         // unauthorized interface 
        bean. setUnauthorizedUrl ( "/ 403" );
         // configuration will not be blocked links
        Map<String, String> map = new LinkedHashMap<>();
        map.put("/doLogin", "anon");
        map.put("/**", "authc");
        bean.setFilterChainDefinitionMap(map);
        return bean;
    }
}

3, the controller Test Method

package com.example.demo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @GetMapping("/login")
    public String  login() {
        return "登录页面...";
    }

    @PostMapping("/doLogin")
    public String doLogin(String userName, String password) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(userName, password));
            return "登录成功!";
        } catch (UnknownAccountException e) {
            return e.getMessage();
        } catch(AuthenticationException E) {
             return "failed login, password is wrong!" ; 
        } 
    } 

    // If not the first landing, access will jump / the Login 
    @GetMapping ( "/ index" )
     public String index () {
         return "index" ; 
    } 

    @GetMapping ( "/ 403" )
     public String unauthorizedRole () {
         return "no authority" ; 
    } 
}

Method two: introducing dependencies shiro-spring-boot-web-starter

1, pom.xml delete shiro-spring, the introduction of shiro-spring-boot-web-starter

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-web-starter</artifactId>
            <version>1.4.2</version>
        </dependency>

2, create and configure the Realm shiro

(1) Create a Realm, code and method of the same.
(2) Configuration Shiro

package com.example.demo.config;

import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
    @Bean
    MyRealm myRealm() {
        return new MyRealm();
    }

    @Bean
    DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myRealm());
        return manager;
    }

    @Bean
    ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        definition.addPathDefinition("/doLogin", "anon");
        definition.addPathDefinition("/**", "authc");
        return definition;
    }
}

(3) application.yml Configuration

shiro:
  unauthorizedUrl: /403
  successUrl: /index
  loginUrl: /login

 

Guess you like

Origin www.cnblogs.com/gdjlc/p/12006635.html