spring security test

spring security test

1,导入依赖

  <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>
          <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframework.securitygroupId>
            <artifactId>spring-security-testartifactId>
            <scope>testscope>
        dependency>

2,代码示例

mockMvc 配置security环境

@WithMockUser 模拟用户,手动指定用户名和授权

@WithAnonymousUser 模拟匿名用户

@WithUserDetails 模拟用户,给定用户名,通过自定义UserDetailService来认证

@WithSecurityContext 通过SecurityContext构造器模拟用户

package com.customer.securityloginmethods.controller;

import com.alibaba.fastjson.JSON;
import com.customer.securityloginmethods.entity.UserInfo;
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.security.test.context.support.WithMockUser;
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.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;

/**
 * @WithMockUser 模拟用户,手动指定用户名和授权
 * @WithAnonymousUser 模拟匿名用户
 * @WithUserDetails 模拟用户,给定用户名,通过自定义UserDetailService来认证
 * @WithSecurityContext 通过SecurityContext构造器模拟用户
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class LoginControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void beforeTest(){
        mockMvc = 
 				//配置ServletContext上下文           
            MockMvcBuilders.webAppContextSetup(webApplicationContext)
            //设置springSecurity配置
                .apply(springSecurity())
                .build();
    }
	
    @Test
    public void testLogin() throws Exception {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("xch");
        userInfo.setPassword("123");
        mockMvc.perform(MockMvcRequestBuilders.post("/login")
                .content(JSON.toJSONString(userInfo))
                .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
        ).andExpect(authenticated());
    }


    @Test
    //模拟登陆用户
    @WithMockUser(username = "xch",roles = "admin")
    public void testAdminAccess() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/adminAccess"))
                .andDo(MockMvcResultHandlers.print());
    }

    @Test
    public void testLogOut() throws Exception {
      mockMvc.perform(MockMvcRequestBuilders.get("logOut"))
              .andExpect(unauthenticated());
    }

}

package com.customer.securityloginmethods.controller;

import com.customer.securityloginmethods.config.common.ResponseBean;
import com.customer.securityloginmethods.entity.UserInfo;
import com.customer.securityloginmethods.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * @author xch
 * @since 2019/6/12 8:53
 **/
@RestController
@Slf4j(topic = "spring security 属性")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public ResponseBean login(@RequestBody UserInfo userInfo) {
        loginService.login(userInfo.getUsername(),userInfo.getPassword());
        return ResponseBean.builder().code(0).msg("登陆成功").build();
    }

    @GetMapping("/logOut")
    public ResponseBean logOut(){
        SecurityContextHolder.clearContext();
        return ResponseBean.builder().code(0).msg("退出成功").build();
    }


    @PreAuthorize("hasAnyRole('admin')")
    @RequestMapping("adminAccess")
    public String adminAccess(){
        log.info("权限:{}",  SecurityContextHolder.getContext().getAuthentication().getAuthorities());
        log.info("用户名:{}",SecurityContextHolder.getContext().getAuthentication().getName());
        log.info("userDetail:{}",SecurityContextHolder.getContext().getAuthentication().getDetails());
        log.info("principal: {}",SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        log.info("credentials:{}",SecurityContextHolder.getContext().getAuthentication().getDetails());
        return  "admin访问成功";
    }

    @PreAuthorize("hasAnyRole('usr')")
    @RequestMapping("usrAccess")
    public String usrAccess(){
        return "usr访问成功";
    }

    @RequestMapping("authenticated")
    public String authenticated(){
        return "需要登陆才能访问的url路径";
    }

    @RequestMapping("annymous")
    public String annymous(){
        System.out.println( SecurityContextHolder.getContext().getAuthentication().getAuthorities());
        return "不需要登陆就能访问成功";
    }
}

项目地址

你可能感兴趣的:(java)