cn.bestwu.api.sign.DefaultApiSign Maven / Gradle / Ivy
package cn.bestwu.api.sign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration;
import javax.servlet.http.HttpServletRequest;
/**
* 默认签名算法
*
* @author Peter Wu
*/
public class DefaultApiSign extends ApiSignAdpter {
@Autowired
private HttpServletRequest request;
@Autowired
private AuthorizationServerEndpointsConfiguration serverEndpointsConfiguration;
@Override protected String loadClientSignKeyByClientId(String client_id) {
return serverEndpointsConfiguration.getEndpointsConfigurer().getClientDetailsService().loadClientByClientId(client_id).getClientSecret();
}
@Override
protected boolean isAdmin() {
String isAdminKey = "IS_ADMIN";
Boolean isAdmin = (Boolean) request.getAttribute(isAdminKey);
if (isAdmin == null) {
isAdmin = hasAuthority(SecurityContextHolder.getContext().getAuthentication(), "ROLE_ADMIN");
request.setAttribute(isAdminKey, isAdmin);
}
return isAdmin;
}
/**
* @param authentication 认证信息
* @param authority 权限
* @return 认证信息是否包含指定权限
*/
private boolean hasAuthority(Authentication authentication, String authority) {
for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
if (grantedAuthority.getAuthority().equals(authority)) {
return true;
}
}
return false;
}
}