Skip to content

Commit

Permalink
优化权限
Browse files Browse the repository at this point in the history
  • Loading branch information
zhou-hao committed Sep 11, 2018
1 parent 885c400 commit 1f9f788
Show file tree
Hide file tree
Showing 17 changed files with 460 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@
public interface AuthenticationManager {
String USER_AUTH_CACHE_NAME = "user-auth-";

/**
* 进行授权操作
*
* @param request 授权请求
* @return 授权成功则返回用户权限信息
*/
Authentication authenticate(AuthenticationRequest request);

/**
* 根据用户ID获取权限信息
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package org.hswebframework.web.authorization;

import java.io.Serializable;

/**
* @author zhouhao
* @since 3.0.0-RC
*/
public interface AuthenticationRequest extends Serializable {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package org.hswebframework.web.authorization.simple;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hswebframework.web.authorization.AuthenticationRequest;

/**
* @author zhouhao
* @since 3.0.0-RC
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class PlainTextUsernamePasswordAuthenticationRequest implements AuthenticationRequest {
private String username;

private String password;
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
package org.hswebframework.web.authorization;

import com.alibaba.fastjson.JSON;
import org.hswebframework.web.authorization.access.DataAccessConfig;
import org.hswebframework.web.authorization.access.FieldFilterDataAccessConfig;
import org.hswebframework.web.authorization.access.ScopeDataAccessConfig;
import org.hswebframework.web.authorization.builder.AuthenticationBuilder;
import org.hswebframework.web.authorization.exception.UnAuthorizedException;
import org.hswebframework.web.authorization.simple.SimpleFiledScopeDataAccessConfig;
import org.hswebframework.web.authorization.simple.builder.SimpleAuthenticationBuilder;
import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
import org.hswebframework.web.authorization.token.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import static org.hswebframework.web.authorization.Permission.scope;
import static org.junit.Assert.*;

public class AuthenticationTests {
Expand Down Expand Up @@ -102,6 +94,11 @@ public void testGetSetCurrentUser() {

//初始化权限管理器,用于获取用户的权限信息
AuthenticationManager authenticationManager = new AuthenticationManager() {
@Override
public Authentication authenticate(AuthenticationRequest request) {
return null;
}

@Override
public Authentication getByUserId(String userId) {
if (userId.equals("admin")) {
Expand Down
28 changes: 28 additions & 0 deletions hsweb-authorization/hsweb-authorization-basic/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,34 @@
<groupId>org.hswebframework</groupId>
<artifactId>hsweb-easy-orm-rdb</artifactId>
</dependency>

<dependency>
<groupId>org.hswebframework.web</groupId>
<artifactId>hsweb-spring-boot-starter</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.hswebframework.web</groupId>
<artifactId>hsweb-tests</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.hswebframework.web</groupId>
<artifactId>hsweb-commons-controller</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package org.hswebframework.web.authorization.basic.configuration;

import org.hswebframework.web.authorization.AuthenticationManager;
import org.hswebframework.web.authorization.access.DataAccessController;
import org.hswebframework.web.authorization.access.DataAccessHandler;
import org.hswebframework.web.authorization.basic.aop.AopMethodAuthorizeDefinitionParser;
import org.hswebframework.web.authorization.basic.embed.EmbedAuthenticationManager;
import org.hswebframework.web.authorization.basic.handler.DefaultAuthorizingHandler;
import org.hswebframework.web.authorization.basic.handler.access.DefaultDataAccessController;
import org.hswebframework.web.authorization.basic.web.*;
Expand All @@ -11,6 +13,8 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
Expand Down Expand Up @@ -59,12 +63,18 @@ public WebMvcConfigurer webUserTokenInterceptorConfigurer(UserTokenManager userT
return new WebMvcConfigurerAdapter() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new WebUserTokenInterceptor(userTokenManager, userTokenParser,parser));
registry.addInterceptor(new WebUserTokenInterceptor(userTokenManager, userTokenParser, parser));
super.addInterceptors(registry);
}
};
}

@Bean
@ConditionalOnMissingBean(AuthenticationManager.class)
public AuthenticationManager embedAuthenticationManager() {
return new EmbedAuthenticationManager();
}

@Bean
public UserOnSignIn userOnSignIn(UserTokenManager userTokenManager) {
return new UserOnSignIn(userTokenManager);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package org.hswebframework.web.authorization.basic.embed;

import lombok.Getter;
import lombok.Setter;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.AuthenticationManager;
import org.hswebframework.web.authorization.AuthenticationRequest;
import org.hswebframework.web.authorization.builder.DataAccessConfigBuilderFactory;
import org.hswebframework.web.authorization.simple.PlainTextUsernamePasswordAuthenticationRequest;
import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
import org.hswebframework.web.validate.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
* @author zhouhao
* @since 3.0.0-RC
*/
@ConfigurationProperties(prefix = "hsweb")
public class EmbedAuthenticationManager implements AuthenticationManager {

private Map<String, Authentication> authentications = new HashMap<>();

@Autowired(required = false)
private DataAccessConfigBuilderFactory dataAccessConfigBuilderFactory = new SimpleDataAccessConfigBuilderFactory();

@Getter
@Setter
private Map<String, EmbedAuthenticationProperties> users = new HashMap<>();

@PostConstruct
public void init() {
users.forEach((id, properties) -> {
if (StringUtils.isEmpty(properties.getId())) {
properties.setId(id);
}
for (EmbedAuthenticationProperties.PermissionInfo permissionInfo : properties.getPermissions()) {
for (Map<String, Object> objectMap : permissionInfo.getDataAccesses()) {
for (Map.Entry<String, Object> stringObjectEntry : objectMap.entrySet()) {
if (stringObjectEntry.getValue() instanceof Map) {
Map mapVal = ((Map) stringObjectEntry.getValue());
boolean maybeIsList = mapVal.keySet().stream().allMatch(org.hswebframework.utils.StringUtils::isInt);
if (maybeIsList) {
stringObjectEntry.setValue(mapVal.values());
}
}
}
}
}
});
}

@Override
public Authentication authenticate(AuthenticationRequest request) {
if (request instanceof PlainTextUsernamePasswordAuthenticationRequest) {
return sync(users.values().stream()
.filter(user ->
((PlainTextUsernamePasswordAuthenticationRequest) request).getUsername().equals(user.getUsername())
&& ((PlainTextUsernamePasswordAuthenticationRequest) request).getPassword().equals(user.getPassword()))
.findFirst()
.map(properties -> properties.toAuthentication(dataAccessConfigBuilderFactory))
.orElseThrow(() -> new ValidationException("用户不存在")));
}

throw new UnsupportedOperationException("不支持的授权类型:" + request);

}

@Override
public Authentication getByUserId(String userId) {
return authentications.get(userId);
}

@Override
public Authentication sync(Authentication authentication) {
authentications.put(authentication.getUser().getId(), authentication);
return authentication;
}

void addAuthentication(Authentication authentication) {
sync(authentication);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package org.hswebframework.web.authorization.basic.embed;

import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.Setter;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.Permission;
import org.hswebframework.web.authorization.Role;
import org.hswebframework.web.authorization.builder.DataAccessConfigBuilderFactory;
import org.hswebframework.web.authorization.simple.SimpleAuthentication;
import org.hswebframework.web.authorization.simple.SimplePermission;
import org.hswebframework.web.authorization.simple.SimpleRole;
import org.hswebframework.web.authorization.simple.SimpleUser;

import java.util.*;
import java.util.stream.Collectors;

/**
* <pre>
* hsweb:
* users:
* admin:
* name: 超级管理员
* username: admin
* password: admin
* roles:
* - id: admin
* name: 管理员
* - id: user
* name: 用户
* permissions:
* - id: user-manager
* actions: *
* dataAccesses:
* - action: query
* type: DENY_FIELDS
* fields: password,salt
* </pre>
*
* @author zhouhao
* @since 3.0.0-RC
*/
@Getter
@Setter
public class EmbedAuthenticationProperties {

private String id;

private String name;

private String username;

private String type;

private String password;

private List<SimpleRole> roles = new ArrayList<>();

private List<PermissionInfo> permissions = new ArrayList<>();

@Getter
@Setter
public static class PermissionInfo {
private String id;

private Set<String> actions = new HashSet<>();

private List<Map<String, Object>> dataAccesses = new ArrayList<>();
}

public Authentication toAuthentication(DataAccessConfigBuilderFactory factory) {
SimpleAuthentication authentication = new SimpleAuthentication();
SimpleUser user = new SimpleUser();
user.setId(id);
user.setName(name);
user.setUsername(username);
user.setType(type);
authentication.setUser(user);
authentication.setRoles((List) roles);
List<Permission> permissionList = permissions.stream()
.map(info -> {
SimplePermission permission = new SimplePermission();
permission.setId(info.getId());
permission.setActions(info.getActions());
permission.setDataAccesses(info.getDataAccesses()
.stream().map(conf -> factory.create()
.fromJson(JSON.toJSONString(conf))
.build()).collect(Collectors.toSet()));
return permission;

}).collect(Collectors.toList());

authentication.setPermissions(permissionList);
return authentication;
}

}
Loading

0 comments on commit 1f9f788

Please sign in to comment.