CAS FIX

上级 4c86d686
...@@ -46,6 +46,17 @@ public class BasicAuthentication implements Authentication { ...@@ -46,6 +46,17 @@ public class BasicAuthentication implements Authentication {
grantedAuthority.add(new SimpleGrantedAuthority("ORDINARY_USER")); 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 @Override
public String getName() { public String getName() {
return "Basic Authentication"; return "Basic Authentication";
......
...@@ -22,6 +22,7 @@ import org.maxkey.web.WebConstants; ...@@ -22,6 +22,7 @@ import org.maxkey.web.WebConstants;
import org.maxkey.web.WebContext; import org.maxkey.web.WebContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.authentication.WebAuthenticationDetails;
...@@ -103,4 +104,34 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider ...@@ -103,4 +104,34 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider
return usernamePasswordAuthenticationToken; 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"));
}
}
} }
...@@ -87,6 +87,7 @@ public abstract class AbstractAuthenticationRealm { ...@@ -87,6 +87,7 @@ public abstract class AbstractAuthenticationRealm {
public abstract boolean passwordMatches(UserInfo userInfo, String password); public abstract boolean passwordMatches(UserInfo userInfo, String password);
public static boolean isAuthenticated() { public static boolean isAuthenticated() {
if (WebContext.getUserInfo() != null) { if (WebContext.getUserInfo() != null) {
return true; return true;
......
...@@ -65,4 +65,8 @@ public class DefaultJdbcAuthenticationRealm extends AbstractAuthenticationRealm ...@@ -65,4 +65,8 @@ public class DefaultJdbcAuthenticationRealm extends AbstractAuthenticationRealm
} }
return passwordMatches; return passwordMatches;
} }
} }
...@@ -8,9 +8,11 @@ ...@@ -8,9 +8,11 @@
MXK_APPS_CAS_DETAILS CD, MXK_APPS_CAS_DETAILS CD,
MXK_APPS APP MXK_APPS APP
WHERE WHERE
APP.ID = #{value} STATUS = 1
AND CD.ID = #{value}
AND CD.ID = APP.ID AND CD.ID = APP.ID
AND STATUS = 1 AND (
APP.ID = #{value}
OR LOWER(CD.SERVICE) LIKE LOWER(CONCAT(#{value},'%'))
)
</select> </select>
</mapper> </mapper>
\ No newline at end of file
...@@ -6,10 +6,12 @@ dependencies { ...@@ -6,10 +6,12 @@ dependencies {
//local jars //local jars
compile fileTree(dir: '../maxkey-lib/*/', include: '*.jar') 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 // 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") compile project(":maxkey-core")
......
...@@ -20,7 +20,6 @@ ...@@ -20,7 +20,6 @@
*/ */
package org.maxkey.authz.cas.endpoint; package org.maxkey.authz.cas.endpoint;
import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
...@@ -55,12 +54,7 @@ public class CasAuthorizeEndpoint extends CasBaseAuthorizeEndpoint{ ...@@ -55,12 +54,7 @@ public class CasAuthorizeEndpoint extends CasBaseAuthorizeEndpoint{
HttpServletResponse response, HttpServletResponse response,
@RequestParam(value=CasConstants.PARAMETER.SERVICE,required=false) String casService){ @RequestParam(value=CasConstants.PARAMETER.SERVICE,required=false) String casService){
AppsCasDetails casDetails=new AppsCasDetails(); AppsCasDetails casDetails=casDetailsService.getAppDetails(casService);
casDetails.setService(casService);
List<AppsCasDetails> casDetailsList=casDetailsService.query(casDetails);
casDetails=(casDetailsList!=null && casDetailsList.size()==1)?casDetailsList.get(0):null;
return buildCasModelAndView(request,response,casDetails); return buildCasModelAndView(request,response,casDetails);
......
...@@ -20,20 +20,17 @@ ...@@ -20,20 +20,17 @@
*/ */
package org.maxkey.authz.cas.endpoint; package org.maxkey.authz.cas.endpoint;
import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.BasicAuthentication; 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.response.ServiceResponseBuilder;
import org.maxkey.authz.cas.endpoint.ticket.CasConstants; import org.maxkey.authz.cas.endpoint.ticket.CasConstants;
import org.maxkey.authz.cas.endpoint.ticket.ServiceTicketImpl; import org.maxkey.authz.cas.endpoint.ticket.ServiceTicketImpl;
import org.maxkey.authz.cas.endpoint.ticket.TicketGrantingTicketImpl; import org.maxkey.authz.cas.endpoint.ticket.TicketGrantingTicketImpl;
import org.maxkey.domain.UserInfo; import org.maxkey.domain.UserInfo;
import org.maxkey.domain.apps.AppsCasDetails; import org.maxkey.domain.apps.AppsCasDetails;
import org.maxkey.persistence.db.PasswordPolicyValidator;
import org.maxkey.web.WebContext; import org.maxkey.web.WebContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -44,7 +41,6 @@ import org.springframework.http.HttpStatus; ...@@ -44,7 +41,6 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
...@@ -61,11 +57,8 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ ...@@ -61,11 +57,8 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
final static Logger _logger = LoggerFactory.getLogger(CasRestV1Endpoint.class); final static Logger _logger = LoggerFactory.getLogger(CasRestV1Endpoint.class);
@Autowired @Autowired
protected PasswordPolicyValidator passwordPolicyValidator; @Qualifier("authenticationProvider")
RealmAuthenticationProvider authenticationProvider ;
@Autowired
@Qualifier("authenticationRealm")
protected AbstractAuthenticationRealm authenticationRealm;
@RequestMapping(value="/authz/cas/v1/tickets", @RequestMapping(value="/authz/cas/v1/tickets",
...@@ -82,33 +75,9 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ ...@@ -82,33 +75,9 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request"); throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request");
} }
AbstractAuthenticationRealm authenticationRealm = BasicAuthentication authentication =new BasicAuthentication(username,password,"CASREST");
(AbstractAuthenticationRealm) WebContext.getBean("authenticationRealm");
UserInfo loadeduserInfo = authenticationRealm.loadUserInfo(username, "");
if (loadeduserInfo != null) {
authenticationRealm.passwordMatches(loadeduserInfo, password);
passwordPolicyValidator.passwordPolicyValid(loadeduserInfo);
WebContext.setUserInfo(loadeduserInfo); authenticationProvider.basicAuthenticate(authentication);
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); TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null);
...@@ -118,11 +87,6 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ ...@@ -118,11 +87,6 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
headers.add("location", location); headers.add("location", location);
return new ResponseEntity<>("Location: " + location, headers ,HttpStatus.CREATED); 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"));
}
} catch (final AuthenticationException e) { } catch (final AuthenticationException e) {
_logger.error("BadCredentialsException ", e); _logger.error("BadCredentialsException ", e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
...@@ -147,16 +111,8 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ ...@@ -147,16 +111,8 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
try { try {
TicketGrantingTicketImpl ticketGrantingTicketImpl = TicketGrantingTicketImpl ticketGrantingTicketImpl =
(TicketGrantingTicketImpl) ticketServices.consumeTicket(ticketGrantingTicket); (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; AppsCasDetails casDetails=casDetailsService.getAppDetails(casService);
}else {
casDetails=casDetailsService.getAppDetails(casService);
}
ServiceTicketImpl serviceTicket=new ServiceTicketImpl(ticketGrantingTicketImpl.getAuthentication(),casDetails); ServiceTicketImpl serviceTicket=new ServiceTicketImpl(ticketGrantingTicketImpl.getAuthentication(),casDetails);
String ticket=ticketServices.createTicket(serviceTicket); String ticket=ticketServices.createTicket(serviceTicket);
...@@ -222,34 +178,10 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ ...@@ -222,34 +178,10 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request"); throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request");
} }
AbstractAuthenticationRealm authenticationRealm = BasicAuthentication authentication =new BasicAuthentication(username,password,"CASREST");
(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");
authenticationProvider.basicAuthenticate(authentication);
UserInfo userInfo =WebContext.getUserInfo();
TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null); TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null);
String ticket=ticketServices.createTicket(ticketGrantingTicket); String ticket=ticketServices.createTicket(ticketGrantingTicket);
...@@ -259,30 +191,25 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ ...@@ -259,30 +191,25 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{
ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(); ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder();
serviceResponseBuilder.setFormat(CasConstants.FORMAT_TYPE.JSON); serviceResponseBuilder.setFormat(CasConstants.FORMAT_TYPE.JSON);
//for user //for user
serviceResponseBuilder.setAttribute("uid", loadeduserInfo.getId()); serviceResponseBuilder.setAttribute("uid", userInfo.getId());
serviceResponseBuilder.setAttribute("displayName",loadeduserInfo.getDisplayName()); serviceResponseBuilder.setAttribute("displayName",userInfo.getDisplayName());
serviceResponseBuilder.setAttribute("firstName", loadeduserInfo.getGivenName()); serviceResponseBuilder.setAttribute("firstName", userInfo.getGivenName());
serviceResponseBuilder.setAttribute("lastname", loadeduserInfo.getFamilyName()); serviceResponseBuilder.setAttribute("lastname", userInfo.getFamilyName());
serviceResponseBuilder.setAttribute("mobile", loadeduserInfo.getMobile()); serviceResponseBuilder.setAttribute("mobile", userInfo.getMobile());
serviceResponseBuilder.setAttribute("birthday", loadeduserInfo.getBirthDate()); serviceResponseBuilder.setAttribute("birthday", userInfo.getBirthDate());
serviceResponseBuilder.setAttribute("gender", loadeduserInfo.getGender()+""); serviceResponseBuilder.setAttribute("gender", userInfo.getGender()+"");
//for work //for work
serviceResponseBuilder.setAttribute("employeeNumber", loadeduserInfo.getEmployeeNumber()); serviceResponseBuilder.setAttribute("employeeNumber", userInfo.getEmployeeNumber());
serviceResponseBuilder.setAttribute("title", loadeduserInfo.getJobTitle()); serviceResponseBuilder.setAttribute("title", userInfo.getJobTitle());
serviceResponseBuilder.setAttribute("email", loadeduserInfo.getWorkEmail()); serviceResponseBuilder.setAttribute("email", userInfo.getWorkEmail());
serviceResponseBuilder.setAttribute("department", loadeduserInfo.getDepartment()); serviceResponseBuilder.setAttribute("department", userInfo.getDepartment());
serviceResponseBuilder.setAttribute("departmentId", loadeduserInfo.getDepartmentId()); serviceResponseBuilder.setAttribute("departmentId", userInfo.getDepartmentId());
serviceResponseBuilder.setAttribute("workRegion",loadeduserInfo.getWorkRegion()); serviceResponseBuilder.setAttribute("workRegion",userInfo.getWorkRegion());
serviceResponseBuilder.success().setUser(loadeduserInfo.getUsername()); serviceResponseBuilder.success().setUser(userInfo.getUsername());
return new ResponseEntity<>(serviceResponseBuilder.serviceResponseBuilder(), headers ,HttpStatus.OK);
}else { return new ResponseEntity<>(serviceResponseBuilder.serviceResponseBuilder(), headers ,HttpStatus.OK);
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"));
}
} catch (final AuthenticationException e) { } catch (final AuthenticationException e) {
_logger.error("BadCredentialsException ", e); _logger.error("BadCredentialsException ", e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
......
...@@ -38,7 +38,7 @@ public class CasDefaultAdapter extends AbstractAuthorizeAdapter { ...@@ -38,7 +38,7 @@ public class CasDefaultAdapter extends AbstractAuthorizeAdapter {
public String base64Attr(String attrValue){ public String base64Attr(String attrValue){
String b64=""; String b64="";
try { try {
b64="base64:"+Base64.encodeBase64String(attrValue.getBytes(Charset_UTF8)); b64=(attrValue == null? "":"base64:"+Base64.encodeBase64String(attrValue.getBytes(Charset_UTF8)));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -49,13 +49,6 @@ public class TicketGrantingTicketImpl extends AbstractTicket implements TicketGr ...@@ -49,13 +49,6 @@ public class TicketGrantingTicketImpl extends AbstractTicket implements TicketGr
*/ */
private static final long serialVersionUID = -8608149809180911599L; 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. * 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; package org.maxkey.web.authorize.endpoint;
/*
import org.pac4j.cas.profile.CasRestProfile; import org.pac4j.cas.profile.CasRestProfile;
import org.pac4j.cas.client.rest.CasRestFormClient; import org.pac4j.cas.client.rest.CasRestFormClient;
import org.pac4j.cas.config.CasConfiguration; import org.pac4j.cas.config.CasConfiguration;
import org.pac4j.cas.credentials.authenticator.CasRestAuthenticator; import org.pac4j.cas.credentials.authenticator.CasRestAuthenticator;
import org.pac4j.cas.profile.CasProfile; 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.context.WebContext;
import org.pac4j.core.credentials.TokenCredentials; import org.pac4j.core.credentials.TokenCredentials;
import org.pac4j.core.credentials.UsernamePasswordCredentials; import org.pac4j.core.credentials.UsernamePasswordCredentials;
...@@ -15,23 +15,24 @@ import org.springframework.mock.web.MockHttpServletResponse; ...@@ -15,23 +15,24 @@ import org.springframework.mock.web.MockHttpServletResponse;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
//https://apereo.github.io/cas/6.0.x/protocol/REST-Protocol.html
public class RestTestClient { public class RestTestClient {
public static void main(String[] args ) throws HttpAction { public static void main(String[] args ) throws HttpAction {
final String casUrlPrefix = "http://localhost:8080/cas"; final String casUrlPrefix = "http://sso.maxkey.top/maxkey/authz/cas/";
String username = args[0]; String username ="admin";
String password = args[1]; String password ="maxkey";
String serviceUrl = args[2]; String serviceUrl = "http://cas.demo.maxkey.top:8080/demo-cas/";
CasConfiguration casConfiguration = new CasConfiguration(casUrlPrefix); CasConfiguration casConfiguration = new CasConfiguration(casUrlPrefix);
final CasRestAuthenticator authenticator = new CasRestAuthenticator(casConfiguration); final CasRestAuthenticator authenticator = new CasRestAuthenticator(casConfiguration);
final CasRestFormClient client = new CasRestFormClient(casConfiguration,"username","password"); final CasRestFormClient client = new CasRestFormClient(casConfiguration,"username","password");
final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse(); final MockHttpServletResponse response = new MockHttpServletResponse();
final WebContext webContext = new JEEContext(request, response); final WebContext webContext = new J2EContext(request, response);
casConfiguration.init(webContext); casConfiguration.init();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,password,"testclient"); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,password);
CasRestAuthenticator restAuthenticator = new CasRestAuthenticator(casConfiguration); CasRestAuthenticator restAuthenticator = new CasRestAuthenticator(casConfiguration);
// authenticate with credentials (validate credentials) // authenticate with credentials (validate credentials)
restAuthenticator.validate(credentials, webContext); restAuthenticator.validate(credentials, webContext);
...@@ -40,12 +41,12 @@ public class RestTestClient { ...@@ -40,12 +41,12 @@ public class RestTestClient {
final TokenCredentials casCredentials = client.requestServiceTicket(serviceUrl, profile, webContext); final TokenCredentials casCredentials = client.requestServiceTicket(serviceUrl, profile, webContext);
// validate service ticket // validate service ticket
final CasProfile casProfile = client.validateServiceTicket(serviceUrl, casCredentials, webContext); final CasProfile casProfile = client.validateServiceTicket(serviceUrl, casCredentials, webContext);
Map<String,Object> attributes = casProfile.getAttributes(); Map<String,Object> attributes = casProfile.getAttributes();
Set<Map.Entry<String,Object>> mapEntries = attributes.entrySet(); Set<Map.Entry<String,Object>> mapEntries = attributes.entrySet();
for (Map.Entry entry : mapEntries) { for (Map.Entry entry : mapEntries) {
System.out.println(entry.getKey() + ":" + entry.getValue()); 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.
先完成此消息的编辑!
想要评论请 注册