SpringBoot 登录接口单元测试(Shiro方式)

SpringBoot 登录接口单元测试

1.针对登录接口获取Token

package com.demo.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.demo.test.Application;
import com.demo.test.req.auth.LoginReq;
import com.demo.test.resp.auth.UserResp;
import org.apache.shiro.SecurityUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.Filter;

import java.io.File;
import java.io.RandomAccessFile;

import static com.demo.test.TokenTest.*;
import static com.deno.test.enums.ResultCode.SUCCESS_RESP;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * 登录接口测试
 *
 * @author earl
 **/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
@Transactional
public class AuthorityControllerTest {

    private MockMvc mockMvc;
    private MockHttpServletRequest mockHttpServletRequest;

    @Autowired
    WebApplicationContext webApplicationContext;

    @Autowired
    private org.apache.shiro.mgt.SecurityManager securityManager;

    @Before
    public void before()   {
        DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(webApplicationContext);
        //构造shiro过滤器,这个名字对应项目shiro配置的bean
        builder.addFilters((Filter) webApplicationContext.getBean("shirFilter"));
        mockMvc = builder.build();
        //初始化shiro环境,因为代码用了shiro的线程上下文环境
        mockHttpServletRequest = new MockHttpServletRequest(webApplicationContext.getServletContext());
        MockHttpSession mockHttpSession = new MockHttpSession(webApplicationContext.getServletContext());
        mockHttpServletRequest.setSession(mockHttpSession);
        SecurityUtils.setSecurityManager(  securityManager);

    }


    @Test
    public void loginSuccessTest() throws Exception {
        LoginReq req = new LoginReq();
        req.setUserName("test");
        req.setPassword("123456");
        req.setRememberMe(0);
        String responseJson = mockMvc.perform( MockMvcRequestBuilders.post("/login")
                .contentType(MediaType.APPLICATION_JSON_UTF8).header(TOKEN_KEY ,  TOKEN_VALUE).header("language","ZH")
                .content(JSONObject.toJSONString(req)))
                .andExpect(status().isOk()).andDo(MockMvcResultHandlers.print()) .andReturn().getResponse().getContentAsString();
        JSONObject json = JSONObject.parseObject(responseJson);
        String resultCode =  json.getString("code");
        Assert.assertEquals(resultCode, SUCCESS_RESP.getCode());

        UserResp userResp =  JSONObject.toJavaObject(json.getJSONObject("data"), UserResp.class);
        Assert.assertNotNull(userResp );
        Assert.assertNotNull(userResp.getToken() );

        //写入到本地的环境中
        File file = new File(TOKEN_PATH);
        if(!file.exists()) {
            file.mkdirs();
        }
        RandomAccessFile tokenFile = new RandomAccessFile(TOKEN_FILE, "rw");
        tokenFile.writeUTF(userResp.getToken());
    }




}

直接在其他接口引用TokenTest的静态变量即可

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 测试token
 *
 * @author earl
 **/
public final class TokenTest {

    private TokenTest(){}

    public static final String TOKEN_KEY = "token";
    public static final String TOKEN_PATH = "D:\\webdatas\\data\\";
    public static final String TOKEN_FILE = TOKEN_PATH+"token.txt";
    public static String TOKEN_VALUE ;

    static {
        try {
            RandomAccessFile file = new RandomAccessFile(TOKEN_FILE,"r"  );
            TOKEN_VALUE =  file.readUTF();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  

}

要在Spring Boot项目中使用Shiro实现接口授权,需要进行以下步骤: 1. 添加Shiro依赖 在pom.xml文件中添加Shiro依赖: ``` <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.5.0</version> </dependency> ``` 2. 配置Shiro 在Spring Boot的配置文件中添加Shiro的配置,如下所示: ``` shiro: filter-chain-definitions: /** = anon /login = anon /logout = logout /api/** = authc security-manager: realm: type: org.apache.shiro.realm.jdbc.JdbcRealm authentication-query: SELECT password FROM users WHERE username = ? user-roles-query: SELECT role_name FROM user_roles WHERE username = ? permissions-query: SELECT permission FROM roles_permissions WHERE role_name = ? ``` 该配置文件中配置了Shiro的过滤链,以及Shiro的安全管理器和Realm。 3. 编写Shiro Realm 编写一个继承自JdbcRealm的Realm类,并实现doGetAuthenticationInfo()和doGetAuthorizationInfo()两个方法,如下所示: ``` public class MyRealm extends JdbcRealm { @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); String password = new String(upToken.getPassword()); // 根据用户名和密码查询数据库,如果查询到了用户,则返回一个封装了该用户信息的AuthenticationInfo对象 // 如果没有查询到用户,则返回null } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); String username = (String) principals.getPrimaryPrincipal(); // 根据用户名查询用户的角色和权限信息,并将其添加到authorizationInfo中 return authorizationInfo; } } ``` 4. 配置ShiroFilterFactoryBean 在Spring Boot的配置文件中配置ShiroFilterFactoryBean,如下所示: ``` @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired MyRealm myRealm) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(new DefaultWebSecurityManager(myRealm)); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/logout", "logout"); filterChainDefinitionMap.put("/api/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } ``` 该配置文件中配置了一个ShiroFilterFactoryBean,并将其与安全管理器和过滤链绑定在一起。 5. 编写接口控制器 编写一个接口控制器,并在该控制器中添加需要授权的接口方法,如下所示: ``` @RestController public class ApiController { @GetMapping("/api/hello") public String hello() { return "Hello, world!"; } @RequiresRoles("admin") @PostMapping("/api/admin") public String admin() { return "Hello, admin!"; } } ``` 上述代码中,hello()方法不需要授权,而admin()方法需要授予admin角色才能访问。 6. 测试接口授权 启动Spring Boot应用程序,并使用curl或Postman等工具测试接口授权。例如,可以使用以下命令测试admin接口: ``` curl -X POST http://localhost:8080/api/admin -H 'Authorization: Basic YWRtaW46YWRtaW4=' ``` 其中,Authorization头中的值是用户名和密码的Base64编码,上述例子中的用户名和密码都是admin。如果授权成功,服务器将返回"Hello, admin!"。如果授权失败,则返回401 Unauthorized错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值