[code quality] [nacos-console] [filter/security] the if nest optimize, the constants export, the Chinese doc fix (#5847)

This commit is contained in:
brotherlu-xcq 2021-05-26 10:11:05 +08:00 committed by GitHub
parent a233563e82
commit 6fccc34bc9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 33 additions and 27 deletions

View File

@ -65,7 +65,7 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
private String resolveToken(HttpServletRequest request) { private String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader(NacosAuthConfig.AUTHORIZATION_HEADER); String bearerToken = request.getHeader(NacosAuthConfig.AUTHORIZATION_HEADER);
if (StringUtils.isNotBlank(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) { if (StringUtils.isNotBlank(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) {
return bearerToken.substring(7); return bearerToken.substring(TOKEN_PREFIX.length());
} }
String jwt = request.getParameter(Constants.ACCESS_TOKEN); String jwt = request.getParameter(Constants.ACCESS_TOKEN);
if (StringUtils.isNotBlank(jwt)) { if (StringUtils.isNotBlank(jwt)) {

View File

@ -63,6 +63,8 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
private static final String LDAP_PREFIX = "LDAP_"; private static final String LDAP_PREFIX = "LDAP_";
private static final String DEFAULT_SECURITY_AUTH = "simple";
@Autowired @Autowired
private NacosUserDetailsServiceImpl userDetailsService; private NacosUserDetailsServiceImpl userDetailsService;
@ -112,11 +114,12 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
private boolean isAdmin(String username) { private boolean isAdmin(String username) {
List<RoleInfo> roleInfos = nacosRoleService.getRoles(username); List<RoleInfo> roleInfos = nacosRoleService.getRoles(username);
if (CollectionUtils.isNotEmpty(roleInfos)) { if (CollectionUtils.isEmpty(roleInfos)) {
for (RoleInfo roleinfo : roleInfos) { return false;
if (GLOBAL_ADMIN_ROLE.equals(roleinfo.getRole())) { }
return true; for (RoleInfo roleinfo : roleInfos) {
} if (GLOBAL_ADMIN_ROLE.equals(roleinfo.getRole())) {
return true;
} }
} }
return false; return false;
@ -126,7 +129,7 @@ public class LdapAuthenticationProvider implements AuthenticationProvider {
Hashtable<String, String> env = new Hashtable<>(); Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY); env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.PROVIDER_URL, ldapUrl);
env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_AUTHENTICATION, DEFAULT_SECURITY_AUTH);
env.put(Context.SECURITY_PRINCIPAL, userNamePattern.replace("{0}", username)); env.put(Context.SECURITY_PRINCIPAL, userNamePattern.replace("{0}", username));
env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.SECURITY_CREDENTIALS, password);

View File

@ -58,6 +58,10 @@ public class NacosAuthConfig extends WebSecurityConfigurerAdapter {
public static final String CONSOLE_RESOURCE_NAME_PREFIX = "console/"; public static final String CONSOLE_RESOURCE_NAME_PREFIX = "console/";
public static final String UPDATE_PASSWORD_ENTRY_POINT = CONSOLE_RESOURCE_NAME_PREFIX + "user/password"; public static final String UPDATE_PASSWORD_ENTRY_POINT = CONSOLE_RESOURCE_NAME_PREFIX + "user/password";
private static final String DEFAULT_ALL_PATH_PATTERN = "/**";
private static final String PROPERTY_IGNORE_URLS = "nacos.security.ignore.urls";
@Autowired @Autowired
private Environment env; private Environment env;
@ -85,12 +89,12 @@ public class NacosAuthConfig extends WebSecurityConfigurerAdapter {
String ignoreUrls = null; String ignoreUrls = null;
if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) {
ignoreUrls = "/**"; ignoreUrls = DEFAULT_ALL_PATH_PATTERN;
} else if (AuthSystemTypes.LDAP.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) { } else if (AuthSystemTypes.LDAP.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) {
ignoreUrls = "/**"; ignoreUrls = DEFAULT_ALL_PATH_PATTERN;
} }
if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) { if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) {
ignoreUrls = env.getProperty("nacos.security.ignore.urls", "/**"); ignoreUrls = env.getProperty(PROPERTY_IGNORE_URLS, DEFAULT_ALL_PATH_PATTERN);
} }
if (StringUtils.isNotBlank(ignoreUrls)) { if (StringUtils.isNotBlank(ignoreUrls)) {
for (String each : ignoreUrls.trim().split(SECURITY_IGNORE_URLS_SPILT_CHAR)) { for (String each : ignoreUrls.trim().split(SECURITY_IGNORE_URLS_SPILT_CHAR)) {
@ -112,19 +116,12 @@ public class NacosAuthConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) { if (StringUtils.isBlank(authConfigs.getNacosAuthSystemType())) {
http http.csrf().disable().cors()// We don't need CSRF for JWT based authentication
.csrf().disable().cors() // We don't need CSRF for JWT based authentication
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll() .and().authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers(LOGIN_ENTRY_POINT).permitAll() .antMatchers(LOGIN_ENTRY_POINT).permitAll()
.and().authorizeRequests().antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() .and().authorizeRequests().antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated()
.and().exceptionHandling().authenticationEntryPoint(new JwtAuthenticationEntryPoint()); .and().exceptionHandling().authenticationEntryPoint(new JwtAuthenticationEntryPoint());
// disable cache // disable cache
http.headers().cacheControl(); http.headers().cacheControl();

View File

@ -51,6 +51,10 @@ public class NacosAuthManager implements AuthManager {
private static final String TOKEN_PREFIX = "Bearer "; private static final String TOKEN_PREFIX = "Bearer ";
private static final String PARAM_USERNAME = "username";
private static final String PARAM_PASSWORD = "password";
@Autowired @Autowired
private JwtTokenManager tokenManager; private JwtTokenManager tokenManager;
@ -152,8 +156,8 @@ public class NacosAuthManager implements AuthManager {
} }
bearerToken = request.getParameter(Constants.ACCESS_TOKEN); bearerToken = request.getParameter(Constants.ACCESS_TOKEN);
if (StringUtils.isBlank(bearerToken)) { if (StringUtils.isBlank(bearerToken)) {
String userName = request.getParameter("username"); String userName = request.getParameter(PARAM_USERNAME);
String password = request.getParameter("password"); String password = request.getParameter(PARAM_PASSWORD);
bearerToken = resolveTokenFromUser(userName, password); bearerToken = resolveTokenFromUser(userName, password);
} }
@ -170,8 +174,8 @@ public class NacosAuthManager implements AuthManager {
} }
bearerToken = request.getHeader(Constants.ACCESS_TOKEN); bearerToken = request.getHeader(Constants.ACCESS_TOKEN);
if (StringUtils.isBlank(bearerToken)) { if (StringUtils.isBlank(bearerToken)) {
String userName = request.getHeader("username"); String userName = request.getHeader(PARAM_USERNAME);
String password = request.getHeader("password"); String password = request.getHeader(PARAM_PASSWORD);
bearerToken = resolveTokenFromUser(userName, password); bearerToken = resolveTokenFromUser(userName, password);
} }

View File

@ -52,6 +52,8 @@ public class NacosRoleServiceImpl {
public static final String GLOBAL_ADMIN_ROLE = "ROLE_ADMIN"; public static final String GLOBAL_ADMIN_ROLE = "ROLE_ADMIN";
private static final int DEFAULT_PAGE_NO = 1;
@Autowired @Autowired
private AuthConfigs authConfigs; private AuthConfigs authConfigs;
@ -74,7 +76,7 @@ public class NacosRoleServiceImpl {
private void reload() { private void reload() {
try { try {
Page<RoleInfo> roleInfoPage = rolePersistService Page<RoleInfo> roleInfoPage = rolePersistService
.getRolesByUserName(StringUtils.EMPTY, 1, Integer.MAX_VALUE); .getRolesByUserName(StringUtils.EMPTY, DEFAULT_PAGE_NO, Integer.MAX_VALUE);
if (roleInfoPage == null) { if (roleInfoPage == null) {
return; return;
} }
@ -91,7 +93,7 @@ public class NacosRoleServiceImpl {
Map<String, List<PermissionInfo>> tmpPermissionInfoMap = new ConcurrentHashMap<>(16); Map<String, List<PermissionInfo>> tmpPermissionInfoMap = new ConcurrentHashMap<>(16);
for (String role : tmpRoleSet) { for (String role : tmpRoleSet) {
Page<PermissionInfo> permissionInfoPage = permissionPersistService Page<PermissionInfo> permissionInfoPage = permissionPersistService
.getPermissions(role, 1, Integer.MAX_VALUE); .getPermissions(role, DEFAULT_PAGE_NO, Integer.MAX_VALUE);
tmpPermissionInfoMap.put(role, permissionInfoPage.getPageItems()); tmpPermissionInfoMap.put(role, permissionInfoPage.getPageItems());
} }
@ -157,7 +159,7 @@ public class NacosRoleServiceImpl {
public List<RoleInfo> getRoles(String username) { public List<RoleInfo> getRoles(String username) {
List<RoleInfo> roleInfoList = roleInfoMap.get(username); List<RoleInfo> roleInfoList = roleInfoMap.get(username);
if (!authConfigs.isCachingEnabled()) { if (!authConfigs.isCachingEnabled()) {
Page<RoleInfo> roleInfoPage = getRolesFromDatabase(username, 1, Integer.MAX_VALUE); Page<RoleInfo> roleInfoPage = getRolesFromDatabase(username, DEFAULT_PAGE_NO, Integer.MAX_VALUE);
if (roleInfoPage != null) { if (roleInfoPage != null) {
roleInfoList = roleInfoPage.getPageItems(); roleInfoList = roleInfoPage.getPageItems();
} }
@ -176,7 +178,7 @@ public class NacosRoleServiceImpl {
public List<PermissionInfo> getPermissions(String role) { public List<PermissionInfo> getPermissions(String role) {
List<PermissionInfo> permissionInfoList = permissionInfoMap.get(role); List<PermissionInfo> permissionInfoList = permissionInfoMap.get(role);
if (!authConfigs.isCachingEnabled()) { if (!authConfigs.isCachingEnabled()) {
Page<PermissionInfo> permissionInfoPage = getPermissionsFromDatabase(role, 1, Integer.MAX_VALUE); Page<PermissionInfo> permissionInfoPage = getPermissionsFromDatabase(role, DEFAULT_PAGE_NO, Integer.MAX_VALUE);
if (permissionInfoPage != null) { if (permissionInfoPage != null) {
permissionInfoList = permissionInfoPage.getPageItems(); permissionInfoList = permissionInfoPage.getPageItems();
} }

View File

@ -17,7 +17,7 @@
# Console Default Properties # Console Default Properties
spring.mvc.view.prefix=/jsp/ spring.mvc.view.prefix=/jsp/
# 响应页面默认后缀 # the default suffix of page
spring.mvc.view.suffix=.jsp spring.mvc.view.suffix=.jsp
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
#logging.level.root=DEBUG #logging.level.root=DEBUG