基本授权:
(我假设您知道如何创建端点,并且您对创建简单的 Spring Boot 应用程序和 React 应用程序都有基本的了解,所以我将只关注授权主题。)
通过基本授权,您的前端应用程序必须在每次调用 API 时发送用户凭据。而且我们必须考虑到您的后端可能在localhost:8080 和前端localhost:3000 上打开,因此我们必须处理CORS。 (更多关于 CORS Cross-Origin Resource Sharing (CORS)
和 Spring Security 中的 CORS Spring Security CORS)
让我们从我们看到端点的安全配置开始。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.cors(withDefaults())
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").authenticated()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers(HttpMethod.GET, "/cars").authenticated()
.anyRequest().authenticated()
.and()
.httpBasic();
}
//and cors configuration
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedHeaders(List.of("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "OPTIONS"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
我们有需要身份验证的 /login 和 /cars 端点。如果您运行后端应用程序并在localhost:8080/login(或/cars 无关紧要)上打开浏览器,则具有基本授权的窗口将在屏幕中间弹出。 Spring Security 中的默认用户名是user,密码在您的控制台中生成。复制粘贴密码就可以通过了。
现在转到前端应用程序。假设我们有一个简单的应用程序,其中包含两个字段:用户名和密码以及按钮:登录。现在我们必须实现逻辑。
...
basicAuthorize = () => {
let username = this.state.username;
let password = this.state.password;
fetch("http://localhost:8080/login", {
headers: {
"Authorization": 'Basic ' + window.btoa(username + ":" + password)
}
}).then(resp => {
console.log(resp);
if (resp.ok) {
this.setState({
isLoginSucces: true});
} else {
this.setState({isLoginSucces: false});
}
return resp.text();
});
}
...
我们有:
- 用户凭据
- 根据MDN web docks Authorization header 上的基本授权规范进行授权的标头
- 如果响应是
ok,我们可以在某处存储用户凭据,并且在下次调用 API 时,我们必须再次包含授权标头。 (但我们不应该将用户敏感数据存储在像 LocalStorage 或 SessionStorage 这样的位置以用于生产但可以用于开发 Storing Credentials in Local Storage)
智威汤逊:
什么是 JWT,您可以在本站 Jwt.io 上阅读。您还可以调试对乞讨有帮助的令牌。
制作身份验证端点和逻辑。
JWT 很难实现,因此创建一些有助于实现这一点的类会很有帮助。
最重要的是:
- JwtTokenRequest tokenRequest - 这是带有
username和password的POJO,只是为了从前端登录获取它并进一步发送。
- JwtTokenResponse,也是 POJO,只是在 cookie 中发送的令牌字符串
- 我还可以通过 TimeZone 设置令牌过期时间。
@PostMapping("/authenticate")
public ResponseEntity<String> createJwtAuthenticationToken(@RequestBody JwtTokenRequest tokenRequest, HttpServletRequest request, HttpServletResponse response, TimeZone timeZone)
{
try
{
JwtTokenResponse accessToken = authenticationService.authenticate(tokenRequest, String.valueOf(request.getRequestURL()), timeZone);
HttpCookie accessTokenCookie = createCookieWithToken("accessToken", accessToken.getToken(), 10 * 60);
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, accessTokenCookie.toString()).body("Authenticated");
}
catch (AuthenticationException e)
{
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
}
}
//creating cookie
private HttpCookie createCookieWithToken(String name, String token, int maxAge)
{
return ResponseCookie.from(name, token)
.httpOnly(true)
.maxAge(maxAge)
.path("/")
.build();
}
负责身份验证和令牌创建的服务
@Service
public class JwtAuthenticationService
{
private AuthenticationManager authenticationManager;
private final String SECRET_KEY = "SecretKey";
public JwtAuthenticationService(AuthenticationManager authenticationManager)
{
this.authenticationManager = authenticationManager;
}
public JwtTokenResponse authenticate(JwtTokenRequest tokenRequest, String url, TimeZone timeZone) throws AuthenticationException
{
UserDetails userDetails = managerAuthentication(tokenRequest.getUsername(), tokenRequest.getPassword());
String token = generateToken(userDetails.getUsername(), url, timeZone);
return new JwtTokenResponse(token);
}
管理身份验证。您不需要手动检查密码是否属于用户名,因为如果您实现了loadByUsername,Spring 将使用此方法加载用户并检查密码。 Manually Authenticate User with Spring Security
private UserDetails managerAuthentication(String username, String password) throws AuthenticationException
{
Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
return (UserDetails) authenticate.getPrincipal();
}
如果没有抛出异常,则表示用户凭据正确,然后我们可以生成 JWT 令牌。
在本例中,我使用的是Java JWT 库,您可以将其添加到pom.xml 文件中。
该方法根据请求中的时区生成token,同时存储信息请求url。
private String generateToken(String username, String url, TimeZone timeZone)
{
try
{
Instant now = Instant.now();
ZonedDateTime zonedDateTimeNow = ZonedDateTime.ofInstant(now, ZoneId.of(timeZone.getID()));
Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
String token = JWT.create()
.withIssuer(url)
.withSubject(username)
.withIssuedAt(Date.from(zonedDateTimeNow.toInstant()))
.withExpiresAt(Date.from(zonedDateTimeNow.plusMinutes(10).toInstant()))
.sign(algorithm);
return token;
}
catch (JWTCreationException e)
{
e.printStackTrace();
throw new JWTCreationException("Exception creating token", e);
}
}
如果一切正常,则令牌存储在 http-only cookie 中。
当我们有令牌时,如果对经过身份验证的端点完成请求,我们必须先过滤该请求。
我们需要添加我们的自定义过滤器:
public class JwtFilter extends OncePerRequestFilter
{
private final String SECRET_KEY = "SecretKey";
}
//or load from other source
public class JwtFilter extends OncePerRequestFilter
{
private final String SECRET_KEY = ApplicationConstants.SECRET_KEY;
}
- 从父类实现方法
- 取决于您从哪里获取令牌,我们只需加载它。在这个例子中,我使用的是 HttpOnly cookie
- 如果 cookie 存在,则进行授权
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException
{
Cookie tokenCookie = null;
if (request.getCookies() != null)
{
for (Cookie cookie : request.getCookies())
{
if (cookie.getName().equals("accessToken"))
{
tokenCookie = cookie;
break;
}
}
}
if (tokenCookie != null)
{
cookieAuthentication(tokenCookie);
}
chain.doFilter(request, response);
}
private void cookieAuthentication(Cookie cookie)
{
UsernamePasswordAuthenticationToken auth = getTokenAuthentication(cookie.getValue());
SecurityContextHolder.getContext().setAuthentication(auth);
}
private UsernamePasswordAuthenticationToken getTokenAuthentication(String token)
{
DecodedJWT decodedJWT = decodeAndVerifyJwt(token);
String subject = decodedJWT.getSubject();
Set<SimpleGrantedAuthority> simpleGrantedAuthority = Collections.singleton(new SimpleGrantedAuthority("USER"));
return new UsernamePasswordAuthenticationToken(subject, null, simpleGrantedAuthority);
}
private DecodedJWT decodeAndVerifyJwt(String token)
{
DecodedJWT decodedJWT = null;
try
{
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY))
.build();
decodedJWT = verifier.verify(token);
} catch (JWTVerificationException e)
{
//Invalid signature/token expired
}
return decodedJWT;
}
现在,请求使用 cookie 中的令牌进行过滤。我们必须在 Spring Security 中添加自定义过滤器:
@Override
protected void configure(HttpSecurity http) throws Exception
{
...
//now 'session' is managed by JWT http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class);
}
在前端你没有太多工作。
在您的请求中,您只需添加withCredentials: 'include',然后cookie 将随请求一起发送。您必须使用'include',因为它是跨域请求。 Request.credentials
示例请求:
fetch('http://localhost:8080/only-already-authenticated-users', {
method: "GET",
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
})