Skip to content

Commit

Permalink
the auth login api
Browse files Browse the repository at this point in the history
  • Loading branch information
wfnuser committed Dec 25, 2018
1 parent 128e8bd commit ba380e6
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;


@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
Expand All @@ -57,9 +58,10 @@ protected void configure(HttpSecurity http) throws Exception {
.authorizeRequests()
// requests for resource and auth api are always allowed
.antMatchers("/", "/*.html", "/favicon.ico", "/**/*.html").permitAll()
.antMatchers("/v1/cs/health").permitAll()
.antMatchers("/v1/auth/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(genericFilterBean(), UsernamePasswordAuthenticationFilter.class);
http.addFilterAfter(genericFilterBean(), UsernamePasswordAuthenticationFilter.class);

// disable cache
http.headers().cacheControl();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.console.controller;

import com.alibaba.nacos.WebSecurityConfig;
import com.alibaba.nacos.console.utils.JWTTokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author <a href="mailto:[email protected]">hxy1991</a>
*/
@RestController("auth")
@RequestMapping("/v1/auth")
public class AuthController {

@Autowired
private JWTTokenUtils jwtTokenUtils;
@Autowired
private AuthenticationManager authenticationManager;

private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

/**
* Whether the Nacos is in broken states or not, and cannot recover except by being restarted
*
* @return HTTP code equal to 200 indicates that Nacos is in right states. HTTP code equal to 500 indicates that
* Nacos is in broken states.
*/

@ResponseBody
@RequestMapping(value = "login", method = RequestMethod.GET)
public String login(HttpServletRequest request, HttpServletResponse response,
@RequestParam("username") String username,
@RequestParam("password") String password) throws Exception {
// 通过用户名和密码创建一个 Authentication 认证对象,实现类为 UsernamePasswordAuthenticationToken
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
// TODO: 去数据库查询是否存在该用户
try {
//通过 AuthenticationManager(默认实现为ProviderManager)的authenticate方法验证 Authentication 对象
Authentication authentication = authenticationManager.authenticate(authenticationToken);
//将 Authentication 绑定到 SecurityContext
SecurityContextHolder.getContext().setAuthentication(authentication);
//生成Token
String token = jwtTokenUtils.createToken(authentication);
//将Token写入到Http头部
response.addHeader(WebSecurityConfig.AUTHORIZATION_HEADER, "Bearer " + token);
return "Bearer " + token;
} catch (BadCredentialsException authentication) {
throw new Exception("密码错误");
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
try {
HttpServletRequest httpReq = (HttpServletRequest) servletRequest;
String jwt = resolveToken(httpReq);
System.out.println(jwt);
//验证JWT是否正确
if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
//获取用户认证信息
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

@Component
Expand All @@ -20,10 +21,10 @@ public class JWTTokenUtils {

private static final String AUTHORITIES_KEY = "auth";

//签名密钥
// 签名密钥
private String secretKey;

//失效日期
// 失效日期
private long tokenValidityInMilliseconds;

@PostConstruct
Expand All @@ -35,6 +36,23 @@ public void init() {

private final static long EXPIRATIONTIME = 432000000;

// 创建Token
public String createToken(Authentication authentication) {
// 获取当前时间戳
long now = (new Date()).getTime();
// 存放过期时间
Date validity;
validity = new Date(now + this.tokenValidityInMilliseconds);

// 创建Token令牌
return Jwts.builder()
.setSubject(authentication.getName())
.claim(AUTHORITIES_KEY, "admin")
.setExpiration(validity)
.signWith(SignatureAlgorithm.HS512, secretKey)
.compact();
}

// 获取用户权限
public Authentication getAuthentication(String token) {
System.out.println("token:" + token);
Expand Down

0 comments on commit ba380e6

Please sign in to comment.