开发配置类
用于自定义拦截配置
package com.example.demo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; /** * @author 小隐乐乐 * @since 2020/11/8 20:20 */ @Configuration public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/api/signin").permitAll() .anyRequest().authenticated() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean @Override public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }
开发登录实体类
用于完成登录实体
package com.example.demo.dto; import com.sun.istack.internal.NotNull; /** * @author 小隐乐乐 * @since 2020/11/8 20:22 */ public class SigninDto { @NotNull private String username; @NotNull private String password; protected SigninDto() {} public SigninDto(String username, String password) { this.username = username; this.password = password; } 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; } }
改造controller
package com.example.demo.controller; import com.example.demo.dto.SigninDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * * @author 小隐乐乐 * @since 2020/11/8 19:44 */ @RestController @RequestMapping("/api") public class HelloController { @Autowired private AuthenticationManager authenticationManager; @GetMapping("/hello") public String hello() { return "hello guys"; } @PostMapping("/signin") public Authentication signIn(@RequestBody @Valid SigninDto signInDto) { return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(signInDto.getUsername(), signInDto.getPassword())); } }
目录结构
此时完成了添加端点signin到自定义拦截链中
测试应用
此时接口api/hello,仍然是没有权限的,我们添加jwt的支持。
添加JWT
依赖添加
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>
开发token生成类
package com.example.demo.jwt; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Base64; import java.util.Date; /** * @author 小隐乐乐 * @since 2020/11/8 20:38 */ @Component public class JwtProvider { private String secretKey; private long validityInMilliseconds; @Autowired public JwtProvider(@Value("${security.jwt.token.secret-key}") String secretKey, @Value("${security.jwt.token.expiration}") long milliseconds) { this.secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); this.validityInMilliseconds = milliseconds; } public String createToken(String username) { //Add the username to the payload Claims claims = Jwts.claims().setSubject(username); //Build the Token Date now = new Date(); return Jwts.builder() .setClaims(claims) .setIssuedAt(now) .setExpiration(new Date(now.getTime() + validityInMilliseconds)) .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); } }