Skip to content

Commit

Permalink
parse the username from token
Browse files Browse the repository at this point in the history
  • Loading branch information
wfnuser committed Jan 2, 2019
1 parent 23c7f29 commit 14b4c64
Show file tree
Hide file tree
Showing 8 changed files with 52 additions and 46 deletions.
27 changes: 15 additions & 12 deletions console/src/main/java/com/alibaba/nacos/WebSecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
Expand Down Expand Up @@ -55,6 +56,13 @@ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
.passwordEncoder(passwordEncoder());
}

@Override
public void configure(WebSecurity web) throws Exception {
// TODO: we should use a better way to match the resources
// requests for resource and auth api are always allowed
web.ignoring().antMatchers("/", "/*.html", "/**/*.js", "/**/*.css", "/favicon.ico", "/**/*.html", "/**/*.map", "/**/*.svg", "/console-fe/public/*", "/**/*.png", "/*.png");
}

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

Expand All @@ -63,29 +71,24 @@ protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll();
} else {
http
// since we use jwt, csrf is not necessary
.csrf().disable()
.authorizeRequests()
.antMatchers("/v1/cs/health").permitAll()
.antMatchers("/v1/auth/**").permitAll()
.anyRequest().authenticated().and()
// custom token authorize exception handler
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.authenticationEntryPoint(unauthorizedHandler).and()
// since we use jwt, session is not necessary
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
// TODO: we should use a better way to match the resources
// requests for resource and auth api are always allowed
.antMatchers("/", "/*.html", "/**/*.js", "/**/*.css", "/favicon.ico", "/**/*.html", "/**/*.svg", "/console-fe/public/*", "/**/*.png", "/*.png").permitAll()
.antMatchers("/v1/cs/health").permitAll()
.antMatchers("/v1/auth/**").permitAll()
.anyRequest().authenticated();
// since we use jwt, csrf is not necessary
.csrf().disable();
http.addFilterBefore(genericFilterBean(), UsernamePasswordAuthenticationFilter.class);

// disable cache
http.headers().cacheControl();
}
}


@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,12 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
HttpServletResponse httpRes = (HttpServletResponse) servletResponse;

String jwt = resolveToken(httpReq);
// JWT为空,返回401
if (!StringUtils.hasText(jwt)) {
httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
// 验证JWT是否正确
else if (this.tokenProvider.validateToken(jwt)) {
if (this.tokenProvider.validateToken(jwt)) {
//获取用户认证信息
Authentication authentication = this.tokenProvider.getAuthentication(jwt);
//将用户保存到SecurityContext
SecurityContextHolder.getContext().setAuthentication(authentication);
} else {
// 验证失败返回403
httpRes.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
filterChain.doFilter(servletRequest, servletResponse);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

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

@Override
public void commence(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
httpServletResponse.sendError(httpServletResponse.getStatus(), "Invalid token");
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
// 403
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Authentication Failed");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,7 @@ const request = (function(_global) {
success => {},
error => {
// 处理403 forbidden
if (error && error.status === 403) {
if (error && (error.status === 403 || error.status === 401)) {
// 跳转至login页
// TODO: 用 react-router 重写,改造成本比较高,这里先hack
const url = window.location.href;
Expand Down
22 changes: 18 additions & 4 deletions console/src/main/resources/static/console-fe/src/layouts/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import React from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { ConfigProvider } from '@alifd/next';
import { ConfigProvider, Dropdown, Menu } from '@alifd/next';
import siteConfig from '../config';
import { changeLanguage } from '@/reducers/locale';
import { aliwareIntl } from '@/globalLib';
Expand Down Expand Up @@ -44,6 +44,18 @@ class Header extends React.Component {
this.props.history.push('/login');
};

getUsername = () => {
const token = window.localStorage.getItem('token');
if (token) {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
const parsedToken = JSON.parse(window.atob(base64));
console.log(parsedToken);
return parsedToken.sub;
}
return '';
};

render() {
const {
locale = {},
Expand Down Expand Up @@ -87,9 +99,11 @@ class Header extends React.Component {
</a>
{/* if is login page, we will show logout */}
{pathname !== '/login' && (
<span className="logout" onClick={this.logout}>
退出
</span>
<Dropdown trigger={<div className="logout">{this.getUsername()}</div>}>
<Menu>
<Menu.Item onClick={this.logout}>登出</Menu.Item>
</Menu>
</Dropdown>
)}
<span className="language-switch language-switch-primary" onClick={this.switchLang}>
{languageSwitchButton}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,10 @@
}
.header-container .header-body .logout {
float: right;
display: inline-block;
box-sizing: border-box;
margin-right: 40px;
text-align: center;
font-family: PingFangSC-Medium;
color: white;
font-size: 14px;
color: #fff;
opacity: 0.6;
font-family: Avenir-Medium;
margin-right: 40px;
}
.header-container .header-body .language-switch:hover {
opacity: 1;
Expand Down
2 changes: 1 addition & 1 deletion console/src/main/resources/static/css/main.css

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions console/src/main/resources/static/js/main.js

Large diffs are not rendered by default.

0 comments on commit 14b4c64

Please sign in to comment.