Not because see hope to insist, and insist to know there is no hope.

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/16/16367d5da076b749~tplv-t2oaga2asx-image.image

preface

In Spring Security source code analysis xi: Spring Security OAuth2 with JWT and Spring Boot 2.0 We all use the Restlet client-Rest API Testing to test apis protected by Oauth2. In this chapter, we’ll show how to test Oauth2’s API using MockMvc.

Modified pom. XML

Add the spring-security-test dependency

 		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
		</dependency>
Copy the code

Modify MerryyouResourceServerConfig configuration

   @Override
    public void configure(HttpSecurity http) throws Exception {

        // @formatter:off
        http.formLogin()
                .successHandler(appLoginInSuccessHandler)// Successful login handler
                .and()
                .authorizeRequests()
                .antMatchers("/user").hasRole("USER")
                .antMatchers("/forbidden").hasRole("ADMIN")
                .anyRequest().authenticated().and()
                .csrf().disable();

        // @formatter:ON
    }

Copy the code
  • Modify theMerryyouResourceServerConfigConfiguration to add role verification for a specified path.
  • The default role isROLE_USER, as shown in theMyUserDetailsService
@Component
public class MyUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return new User(username, "123456", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); }}Copy the code
  • On whyhasRole("USER")Rather thanhasRole("ROLE_USER")Please refer to:Spring Security: Expression – based permission control
  • @formatter:offand@formatter:ONThis code is not formatted

Add /user and /forbidden request mappings

@GetMapping("/user")
    public Object getCurrentUser1(Authentication authentication, HttpServletRequest request) throws UnsupportedEncodingException {
        log.info("[SecurityOauth2Application] getCurrentUser1 authenticaiton = {}", JsonUtil.toJson(authentication));

        String header = request.getHeader("Authorization");
        String token = StringUtils.substringAfter(header, "bearer ");

        Claims claims = Jwts.parser().setSigningKey(oAuth2Properties.getJwtSigningKey().getBytes("UTF-8")).parseClaimsJws(token).getBody();
        String blog = (String) claims.get("blog");
        log.info("[SecurityOauth2Application] getCurrentUser1 blog = {}", blog);

        return authentication;
    }

    @GetMapping("/forbidden")
    public String getForbidden(a) {
        return "forbidden";
    }
Copy the code
  • /userThe request toUSERrole
  • /forbiddenThe request toADMINrole

Add the test class SecurityOauth2Test

@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = SecurityOauth2Application.class)
@Slf4j
public class Oauth2MvcTest {

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    private MockMvc mockMvc;

    //clientId
    final static String CLIENT_ID = "merryyou";
    //clientSecret
    final static String CLIENT_SECRET = "merryyou";
    / / user name
    final static String USERNAME = "admin";
    / / password
    final static String PASSWORD = "123456";

    private static final String CONTENT_TYPE = "application/json; charset=UTF-8";

    @Before
    public void setup(a) {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilter(springSecurityFilterChain).build();// Initialize the MockMvc object and add the Security filter chain
    }
Copy the code
  • Initialize theOauth2information

obtainAccessToken

  public String obtainAccessToken(a) throws Exception {
        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type"."password");
        params.add("client_id", CLIENT_ID);
        params.add("username", USERNAME);
        params.add("password", PASSWORD);

        // @formatter:off

        ResultActions result = mockMvc.perform(post("/oauth/token")
                .params(params)
                .with(httpBasic(CLIENT_ID, CLIENT_SECRET))
                .accept(CONTENT_TYPE))
                .andExpect(status().isOk())
                .andExpect(content().contentType(CONTENT_TYPE));

        // @formatter:on

        String resultString = result.andReturn().getResponse().getContentAsString();

        JacksonJsonParser jsonParser = new JacksonJsonParser();
// System.out.println(jsonParser.parseMap(resultString).get("access_token").toString());
        return jsonParser.parseMap(resultString).get("access_token").toString();
    }
Copy the code

Test obtainAccessToken

 @Test
    public void getAccessToken(a) throws Exception {
        final String accessToken = obtainAccessToken();
        log.info("access_token={}", accessToken);
    }
Copy the code

Console printing:

access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbImFsbCJdLCJleHAiOjE1MjY0NjEwMz gsImJsb2ciOiJodHRwczovL2xvbmdmZWl6aGVuZy5naXRodWIuaW8vIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6ImE1MmE2NDI4LTcwNz ctNDcwZC05M2MwLTc0ZWNlNjFhYTlkMCIsImNsaWVudF9pZCI6Im1lcnJ5eW91In0.CPmkZmfOkgDII29RMIoMO7ufAe5WFrQDB7SaMDKa128Copy the code

UnauthorizedTest

    /** * unauthorized 401 **@throws Exception
     */
    @Test
    public void UnauthorizedTest(a) throws Exception {
// mockMvc.perform(get("/user")).andExpect(status().isUnauthorized());
        ResultActions actions = mockMvc.perform(get("/user"));
        int status = actions.andReturn().getResponse().getStatus();
        Assert.assertTrue(status == HttpStatus.UNAUTHORIZED.value());
    }
Copy the code
  • unauthorized401

forbiddenTest

   /** * disable access to 403 **@throws Exception
     */
    @Test
    public void forbiddenTest(a) throws Exception {
        final String accessToken = obtainAccessToken();
        log.info("access_token={}", accessToken);
        mockMvc.perform(get("/forbidden").header("Authorization"."bearer " + accessToken)).andExpect(status().isForbidden());
    }
Copy the code
  • Blocking access403

accessTokenOk

    /** * allows access to 200 **@throws Exception
     */
    @Test
    public void accessTokenOk(a) throws Exception {
        final String accessToken = obtainAccessToken();
        log.info("access_token={}", accessToken);
        mockMvc.perform(get("/user").header("Authorization"."bearer " + accessToken)).andExpect(status().isOk());
    }
Copy the code
  • Allow access to200

The code download

  • Github:github.com/longfeizhen…
  • Gitee:gitee.com/merryyou/se…

Recommend the article

  1. Java creates the blockchain family
  2. Spring Security source code analysis series
  3. Spring Data Jpa series
  4. All about Trees in Data Structures (Java Edition)
  5. SpringBoot+Docker+Git+Jenkins realize easy continuous integration and continuous deployment

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/16/16367d5da0881498~tplv-t2oaga2asx-image.image

🙂🙂🙂 focus on wechat small program Java architect journey Bored on the commute? Still reading novels, news? Don’t know how to improve your skills? Here’s the Java architecture article you need. 1.5W + Java engineers are reading it. What are you waiting for?