CAS FIX

上级 4c86d686
......@@ -46,6 +46,17 @@ public class BasicAuthentication implements Authentication {
grantedAuthority.add(new SimpleGrantedAuthority("ORDINARY_USER"));
}
/**
* BasicAuthentication.
*/
public BasicAuthentication(String username,String password,String authType) {
this.username = username;
this.password = password;
this.authType = authType;
grantedAuthority = new ArrayList<GrantedAuthority>();
grantedAuthority.add(new SimpleGrantedAuthority("ROLE_USER"));
grantedAuthority.add(new SimpleGrantedAuthority("ORDINARY_USER"));
}
@Override
public String getName() {
return "Basic Authentication";
......
......@@ -22,6 +22,7 @@ import org.maxkey.web.WebConstants;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
......@@ -103,4 +104,34 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
return usernamePasswordAuthenticationToken;
}
public Authentication basicAuthenticate(Authentication authentication) {
BasicAuthentication basicAuth = (BasicAuthentication) authentication;
UserInfo loadeduserInfo = loadUserInfo(basicAuth.getUsername(), "");
if (loadeduserInfo != null) {
authenticationRealm.passwordMatches(loadeduserInfo, basicAuth.getPassword());
authenticationRealm.getPasswordPolicyValidator().passwordPolicyValid(loadeduserInfo);
WebContext.setUserInfo(loadeduserInfo);
authentication.setAuthenticated(true);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
authentication, "PASSWORD", authenticationRealm.grantAuthority(loadeduserInfo));
WebContext.setAuthentication(authenticationToken);
WebContext.setUserInfo(loadeduserInfo);
authenticationRealm.insertLoginHistory(loadeduserInfo, basicAuth.getAuthType(), "", "", "SUCCESS");
return authenticationToken;
}else {
String message = WebContext.getI18nValue("login.error.username");
_logger.debug("login user " + basicAuth.getUsername() + " not in this System ." + message);
throw new BadCredentialsException(WebContext.getI18nValue("login.error.username"));
}
}
}
......@@ -86,6 +86,7 @@ public abstract class AbstractAuthenticationRealm {
}
public abstract boolean passwordMatches(UserInfo userInfo, String password);
public static boolean isAuthenticated() {
if (WebContext.getUserInfo() != null) {
......
......@@ -65,4 +65,8 @@ public class DefaultJdbcAuthenticationRealm extends AbstractAuthenticationRealm
}
return passwordMatches;
}
}
......@@ -8,9 +8,11 @@
MXK_APPS_CAS_DETAILS CD,
MXK_APPS APP
WHERE
APP.ID = #{value}
AND CD.ID = #{value}
STATUS = 1
AND CD.ID = APP.ID
AND STATUS = 1
AND (
APP.ID = #{value}
OR LOWER(CD.SERVICE) LIKE LOWER(CONCAT(#{value},'%'))
)
</select>
</mapper>
\ No newline at end of file
......@@ -6,10 +6,12 @@ dependencies {
//local jars
compile fileTree(dir: '../maxkey-lib/*/', include: '*.jar')
// https://mvnrepository.com/artifact/org.jasig.cas.client/cas-client-core
testCompile group: 'org.jasig.cas.client', name: 'cas-client-core', version: '3.6.1'
testCompile group: 'org.pac4j', name: 'pac4j-core', version: '3.1.0'
testCompile group: 'org.pac4j', name: 'pac4j-core', version: '3.8.3'
// https://mvnrepository.com/artifact/org.pac4j/pac4j-cas
testCompile group: 'org.pac4j', name: 'pac4j-cas', version: '3.1.0'
testCompile group: 'org.pac4j', name: 'pac4j-cas', version: '3.8.3'
compile project(":maxkey-core")
......
......@@ -20,7 +20,6 @@
*/
package org.maxkey.authz.cas.endpoint;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
......@@ -54,13 +53,8 @@ public class CasAuthorizeEndpoint extends CasBaseAuthorizeEndpoint{
HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value=CasConstants.PARAMETER.SERVICE,required=false) String casService){
AppsCasDetails casDetails=new AppsCasDetails();
casDetails.setService(casService);
List<AppsCasDetails> casDetailsList=casDetailsService.query(casDetails);
casDetails=(casDetailsList!=null && casDetailsList.size()==1)?casDetailsList.get(0):null;
AppsCasDetails casDetails=casDetailsService.getAppDetails(casService);
return buildCasModelAndView(request,response,casDetails);
......
......@@ -20,20 +20,17 @@
*/
package org.maxkey.authz.cas.endpoint;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.BasicAuthentication;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.RealmAuthenticationProvider;
import org.maxkey.authz.cas.endpoint.response.ServiceResponseBuilder;
import org.maxkey.authz.cas.endpoint.ticket.CasConstants;
import org.maxkey.authz.cas.endpoint.ticket.ServiceTicketImpl;
import org.maxkey.authz.cas.endpoint.ticket.TicketGrantingTicketImpl;
import org.maxkey.domain.UserInfo;
import org.maxkey.domain.apps.AppsCasDetails;
import org.maxkey.persistence.db.PasswordPolicyValidator;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -44,7 +41,6 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
......@@ -60,12 +56,9 @@ import org.springframework.web.bind.annotation.RequestParam;
public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
final static Logger _logger = LoggerFactory.getLogger(CasRestV1Endpoint.class);
@Autowired
protected PasswordPolicyValidator passwordPolicyValidator;
@Autowired
@Qualifier("authenticationRealm")
protected AbstractAuthenticationRealm authenticationRealm;
@Qualifier("authenticationProvider")
RealmAuthenticationProvider authenticationProvider ;
@RequestMapping(value="/authz/cas/v1/tickets",
......@@ -82,47 +75,18 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request");
}
AbstractAuthenticationRealm authenticationRealm =
(AbstractAuthenticationRealm) WebContext.getBean("authenticationRealm");
UserInfo loadeduserInfo = authenticationRealm.loadUserInfo(username, "");
if (loadeduserInfo != null) {
authenticationRealm.passwordMatches(loadeduserInfo, password);
passwordPolicyValidator.passwordPolicyValid(loadeduserInfo);
WebContext.setUserInfo(loadeduserInfo);
BasicAuthentication authentication =new BasicAuthentication();
authentication.setUsername(username);
authentication.setPassword(password);
authentication.setAuthType("basic");
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
new UsernamePasswordAuthenticationToken(
authentication,
"PASSWORD",
authenticationRealm.grantAuthority(loadeduserInfo)
);
authentication.setAuthenticated(true);
WebContext.setAuthentication(usernamePasswordAuthenticationToken);
WebContext.setUserInfo(loadeduserInfo);
authenticationRealm.insertLoginHistory(loadeduserInfo, "CAS", "", "", "SUCCESS");
TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null);
String ticket=ticketServices.createTicket(ticketGrantingTicket);
String location = applicationConfig.getServerPrefix()+"/authz/cas/v1/tickets/" + ticket;
HttpHeaders headers = new HttpHeaders();
headers.add("location", location);
return new ResponseEntity<>("Location: " + location, headers ,HttpStatus.CREATED);
}else {
String message = WebContext.getI18nValue("login.error.username");
_logger.debug("login user " + username + " not in this System ." + message);
throw new BadCredentialsException(WebContext.getI18nValue("login.error.username"));
}
BasicAuthentication authentication =new BasicAuthentication(username,password,"CASREST");
authenticationProvider.basicAuthenticate(authentication);
TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null);
String ticket=ticketServices.createTicket(ticketGrantingTicket);
String location = applicationConfig.getServerPrefix()+"/authz/cas/v1/tickets/" + ticket;
HttpHeaders headers = new HttpHeaders();
headers.add("location", location);
return new ResponseEntity<>("Location: " + location, headers ,HttpStatus.CREATED);
} catch (final AuthenticationException e) {
_logger.error("BadCredentialsException ", e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
......@@ -147,16 +111,8 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
try {
TicketGrantingTicketImpl ticketGrantingTicketImpl =
(TicketGrantingTicketImpl) ticketServices.consumeTicket(ticketGrantingTicket);
AppsCasDetails casDetails=new AppsCasDetails();
if(casService.startsWith("http")) {
casDetails.setService(casService);
List<AppsCasDetails> casDetailsList=casDetailsService.query(casDetails);
casDetails=(casDetailsList!=null && casDetailsList.size()==1)?casDetailsList.get(0):null;
}else {
casDetails=casDetailsService.getAppDetails(casService);
}
AppsCasDetails casDetails=casDetailsService.getAppDetails(casService);
ServiceTicketImpl serviceTicket=new ServiceTicketImpl(ticketGrantingTicketImpl.getAuthentication(),casDetails);
String ticket=ticketServices.createTicket(serviceTicket);
......@@ -222,67 +178,38 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request");
}
AbstractAuthenticationRealm authenticationRealm =
(AbstractAuthenticationRealm) WebContext.getBean("authenticationRealm");
UserInfo loadeduserInfo = authenticationRealm.loadUserInfo(username, "");
if (loadeduserInfo != null) {
authenticationRealm.passwordMatches(loadeduserInfo, password);
passwordPolicyValidator.passwordPolicyValid(loadeduserInfo);
WebContext.setUserInfo(loadeduserInfo);
BasicAuthentication authentication =new BasicAuthentication();
authentication.setUsername(username);
authentication.setPassword(password);
authentication.setAuthType("basic");
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
new UsernamePasswordAuthenticationToken(
authentication,
"PASSWORD",
authenticationRealm.grantAuthority(loadeduserInfo)
);
authentication.setAuthenticated(true);
WebContext.setAuthentication(usernamePasswordAuthenticationToken);
WebContext.setUserInfo(loadeduserInfo);
authenticationRealm.insertLoginHistory(loadeduserInfo, "CAS", "", "", "SUCCESS");
TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null);
String ticket=ticketServices.createTicket(ticketGrantingTicket);
String location = applicationConfig.getServerPrefix()+"/authz/cas/v1/tickets/" + ticket;
HttpHeaders headers = new HttpHeaders();
headers.add("location", location);
ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder();
serviceResponseBuilder.setFormat(CasConstants.FORMAT_TYPE.JSON);
//for user
serviceResponseBuilder.setAttribute("uid", loadeduserInfo.getId());
serviceResponseBuilder.setAttribute("displayName",loadeduserInfo.getDisplayName());
serviceResponseBuilder.setAttribute("firstName", loadeduserInfo.getGivenName());
serviceResponseBuilder.setAttribute("lastname", loadeduserInfo.getFamilyName());
serviceResponseBuilder.setAttribute("mobile", loadeduserInfo.getMobile());
serviceResponseBuilder.setAttribute("birthday", loadeduserInfo.getBirthDate());
serviceResponseBuilder.setAttribute("gender", loadeduserInfo.getGender()+"");
//for work
serviceResponseBuilder.setAttribute("employeeNumber", loadeduserInfo.getEmployeeNumber());
serviceResponseBuilder.setAttribute("title", loadeduserInfo.getJobTitle());
serviceResponseBuilder.setAttribute("email", loadeduserInfo.getWorkEmail());
serviceResponseBuilder.setAttribute("department", loadeduserInfo.getDepartment());
serviceResponseBuilder.setAttribute("departmentId", loadeduserInfo.getDepartmentId());
serviceResponseBuilder.setAttribute("workRegion",loadeduserInfo.getWorkRegion());
serviceResponseBuilder.success().setUser(loadeduserInfo.getUsername());
return new ResponseEntity<>(serviceResponseBuilder.serviceResponseBuilder(), headers ,HttpStatus.OK);
}else {
String message = WebContext.getI18nValue("login.error.username");
_logger.debug("login user " + username + " not in this System ." + message);
throw new BadCredentialsException(WebContext.getI18nValue("login.error.username"));
}
BasicAuthentication authentication =new BasicAuthentication(username,password,"CASREST");
authenticationProvider.basicAuthenticate(authentication);
UserInfo userInfo =WebContext.getUserInfo();
TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null);
String ticket=ticketServices.createTicket(ticketGrantingTicket);
String location = applicationConfig.getServerPrefix()+"/authz/cas/v1/tickets/" + ticket;
HttpHeaders headers = new HttpHeaders();
headers.add("location", location);
ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder();
serviceResponseBuilder.setFormat(CasConstants.FORMAT_TYPE.JSON);
//for user
serviceResponseBuilder.setAttribute("uid", userInfo.getId());
serviceResponseBuilder.setAttribute("displayName",userInfo.getDisplayName());
serviceResponseBuilder.setAttribute("firstName", userInfo.getGivenName());
serviceResponseBuilder.setAttribute("lastname", userInfo.getFamilyName());
serviceResponseBuilder.setAttribute("mobile", userInfo.getMobile());
serviceResponseBuilder.setAttribute("birthday", userInfo.getBirthDate());
serviceResponseBuilder.setAttribute("gender", userInfo.getGender()+"");
//for work
serviceResponseBuilder.setAttribute("employeeNumber", userInfo.getEmployeeNumber());
serviceResponseBuilder.setAttribute("title", userInfo.getJobTitle());
serviceResponseBuilder.setAttribute("email", userInfo.getWorkEmail());
serviceResponseBuilder.setAttribute("department", userInfo.getDepartment());
serviceResponseBuilder.setAttribute("departmentId", userInfo.getDepartmentId());
serviceResponseBuilder.setAttribute("workRegion",userInfo.getWorkRegion());
serviceResponseBuilder.success().setUser(userInfo.getUsername());
return new ResponseEntity<>(serviceResponseBuilder.serviceResponseBuilder(), headers ,HttpStatus.OK);
} catch (final AuthenticationException e) {
_logger.error("BadCredentialsException ", e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
......
......@@ -38,7 +38,7 @@ public class CasDefaultAdapter extends AbstractAuthorizeAdapter {
public String base64Attr(String attrValue){
String b64="";
try {
b64="base64:"+Base64.encodeBase64String(attrValue.getBytes(Charset_UTF8));
b64=(attrValue == null? "":"base64:"+Base64.encodeBase64String(attrValue.getBytes(Charset_UTF8)));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
......
......@@ -48,13 +48,6 @@ public class TicketGrantingTicketImpl extends AbstractTicket implements TicketGr
* Unique Id for serialization.
*/
private static final long serialVersionUID = -8608149809180911599L;
/**
* The authenticated object for which this ticket was generated for.
*/
@Lob
@Column(name = "AUTHENTICATION", nullable = false, length = Integer.MAX_VALUE)
private Authentication authentication;
/**
* Service that produced a proxy-granting ticket.
......
package org.maxkey.web.authorize.endpoint;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
public class Client {
public static String getTicket(final String server, final String username, final String password,
final String service) {
notNull(server, "server must not be null");
notNull(username, "username must not be null");
notNull(password, "password must not be null");
notNull(service, "service must not be null");
return getServiceTicket(server, getTicketGrantingTicket(server, username, password), service);
}
/**
* 取得ST
* @param server
* @param ticketGrantingTicket
* @param service
*/
private static String getServiceTicket(final String server, final String ticketGrantingTicket, final String service) {
if (ticketGrantingTicket == null)
return null;
final HttpClient client = new HttpClient();
final PostMethod post = new PostMethod(server + "/" + ticketGrantingTicket);
post.setRequestBody(new NameValuePair[] { new NameValuePair("service", service) });
try {
client.executeMethod(post);
final String response = post.getResponseBodyAsString();
switch (post.getStatusCode()) {
case 200:
return response;
default:
warning("Invalid response code (" + post.getStatusCode() + ") from CAS server!");
info("Response (1k): " + response.substring(0, Math.min(1024, response.length())));
break;
}
}
catch (final IOException e) {
warning(e.getMessage());
}
finally {
post.releaseConnection();
}
return null;
}
/**
* @param server
* @param username
* @param password
*/
private static String getTicketGrantingTicket(final String server, final String username, final String password) {
final HttpClient client = new HttpClient();
final PostMethod post = new PostMethod(server);
post.setRequestBody(new NameValuePair[] { new NameValuePair("username", username),
new NameValuePair("password", password) });
try {
client.executeMethod(post);
final String response = post.getResponseBodyAsString();
info("TGT="+response);
switch (post.getStatusCode()) {
case 201: {
final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response);
if (matcher.matches())
return matcher.group(1);
warning("Successful ticket granting request, but no ticket found!");
info("Response (1k): " + response.substring(0, Math.min(1024, response.length())));
break;
}
default:
warning("Invalid response code (" + post.getStatusCode() + ") from CAS server!");
info("Response (1k): " + response.substring(0, Math.min(1024, response.length())));
break;
}
}
catch (final IOException e) {
warning(e.getMessage());
}
finally {
post.releaseConnection();
}
return null;
}
private static void ticketValidate(String serverValidate, String serviceTicket, String service) {
notNull(serviceTicket, "paramter 'serviceTicket' is not null");
notNull(service, "paramter 'service' is not null");
final HttpClient client = new HttpClient();
GetMethod post = null;
try {
post = new GetMethod(serverValidate+"?"+"ticket="+serviceTicket+"&service="+URLEncoder.encode(service, "UTF-8"));
client.executeMethod(post);
final String response = post.getResponseBodyAsString();
info(response);
switch (post.getStatusCode()) {
case 200: {
info("成功取得用户数据");
}
default: {
}
}
} catch (Exception e) {
warning(e.getMessage());
} finally {
//释放资源
post.releaseConnection();
}
}
private static void notNull(final Object object, final String message) {
if (object == null)
throw new IllegalArgumentException(message);
}
public static void main(final String[] args) throws Exception {
final String server = "https://sso.maxkey.top/maxkey/authz/cas/v1/tickets";
final String username = "admin";
final String password = "maxkey";
final String service = "http://cas.demo.maxkey.top:8080/demo-cas/";
final String proxyValidate = "https://sso.maxkey.top/maxkey/authz/cas/p3/serviceValidate";
ticketValidate(proxyValidate, getTicket(server, username, password, service), service);
}
private static void warning(String msg) {
System.out.println(msg);
}
private static void info(String msg) {
System.out.println(msg);
}
}
package org.maxkey.web.authorize.endpoint;
/*
import org.pac4j.cas.profile.CasRestProfile;
import org.pac4j.cas.client.rest.CasRestFormClient;
import org.pac4j.cas.config.CasConfiguration;
import org.pac4j.cas.credentials.authenticator.CasRestAuthenticator;
import org.pac4j.cas.profile.CasProfile;
import org.pac4j.core.context.JEEContext;
import org.pac4j.core.context.J2EContext;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.credentials.TokenCredentials;
import org.pac4j.core.credentials.UsernamePasswordCredentials;
......@@ -15,23 +15,24 @@ import org.springframework.mock.web.MockHttpServletResponse;
import java.util.Map;
import java.util.Set;
//https://apereo.github.io/cas/6.0.x/protocol/REST-Protocol.html
public class RestTestClient {
public static void main(String[] args ) throws HttpAction {
final String casUrlPrefix = "http://localhost:8080/cas";
String username = args[0];
String password = args[1];
String serviceUrl = args[2];
final String casUrlPrefix = "http://sso.maxkey.top/maxkey/authz/cas/";
String username ="admin";
String password ="maxkey";
String serviceUrl = "http://cas.demo.maxkey.top:8080/demo-cas/";
CasConfiguration casConfiguration = new CasConfiguration(casUrlPrefix);
final CasRestAuthenticator authenticator = new CasRestAuthenticator(casConfiguration);
final CasRestFormClient client = new CasRestFormClient(casConfiguration,"username","password");
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
final WebContext webContext = new JEEContext(request, response);
casConfiguration.init(webContext);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,password,"testclient");
final WebContext webContext = new J2EContext(request, response);
casConfiguration.init();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,password);
CasRestAuthenticator restAuthenticator = new CasRestAuthenticator(casConfiguration);
// authenticate with credentials (validate credentials)
restAuthenticator.validate(credentials, webContext);
......@@ -40,12 +41,12 @@ public class RestTestClient {
final TokenCredentials casCredentials = client.requestServiceTicket(serviceUrl, profile, webContext);
// validate service ticket
final CasProfile casProfile = client.validateServiceTicket(serviceUrl, casCredentials, webContext);
Map<String,Object> attributes = casProfile.getAttributes();
Set<Map.Entry<String,Object>> mapEntries = attributes.entrySet();
for (Map.Entry entry : mapEntries) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
client.destroyTicketGrantingTicket(profile,webContext);
//client.destroyTicketGrantingTicket(profile,webContext);
}
}*/
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册