CAS3.5.2 Server集成RESTful API实施详细

        CAS3.5.2 Server提供了Restful API供调用,Restful是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。开启Restful服务需要相关的jar包,CAS3.5.2 Server源码里cas-server-integration-restlet工程支持Restful模块,将其引入到cas-server-webapp工程中即可,下面本站素文宅www.yoodb.com为大家分享一下CAS3.5.2 Server如何集成RESTful API。


在cas-server-webapp工程中需要增加相关的依赖jar包,以满足Restful服务,修改pom.xml文件,增加cas-server-integration-restlet工程jar包依赖maven配置如下:

    <dependency>  
        <groupId>org.jasig.cas</groupId>  
        <artifactId>cas-server-integration-restlet</artifactId>  
        <version>3.4.2.1</version>  
        <type>jar</type>  
</dependency>


其他相关jar包依稀,com.noelios.restlet.ext.servlet.jar

com.noelios.restlet.ext.spring-1.1.0.jar

com.noelios.restlet.jar

org.restlet.ext.spring-1.1.10.jar

org.restlet-1.1.10.jar,pom.xml文件配置如下:

<dependency>
<groupId>org.restlet</groupId>
<artifactId>org.restlet</artifactId>
<version>1.1.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.restlet</groupId>
<artifactId>org.restlet.ext.spring</artifactId>
<version>1.1.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.noelios.restlet</groupId>
<artifactId>com.noelios.restlet.ext.spring</artifactId>
<version>1.1.1</version>
<scope>runtime</scope>
</dependency>
        <dependency>
            <groupId>com.noelios.restlet</groupId>
            <artifactId>com.noelios.restlet.ext.servlet</artifactId>
            <version>1.1.1</version>
            <type>jar</type>
            <scope>runtime</scope>
        </dependency>

此时需要maven数据源Restlet,具体pom.xml配置如下:

<repositories>
<repository>
<id>restlet-repository</id>
<name>Restlet Repository</name>
<url>http://maven.restlet.org</url>
</repository>
</repositories>

上述pom.xml文件配置说白了就是将cas-server-integration-restlet工程里的pom.xml文件内容增加到cas-server-webapp工程中。


2、修改cas-server-webapp工程下web.xml文件,增加Restful的servlet配置,具体如下:

<servlet>
       <servlet-name>restlet</servlet-name>
       <servlet-class>com.noelios.restlet.ext.spring.RestletFrameworkServlet</servlet-class>
       <load-on-startup>1</load-on-startup>
</servlet>       
<servlet-mapping>
       <servlet-name>restlet</servlet-name>
       <url-pattern>/v1/*</url-pattern>
</servlet-mapping>

关于 restlet的其他配置在 Cas3.5.2 Server中已经存在,具体文件地址: /WEB-INF/restlet-servlet.xml文件,配置完成之后直接启动Server。


下面来进行简单登录验证的测试,获取ST票据和TGT票据具体代码如下:

package com.spring.mybatis;

import java.io.IOException;
import java.util.logging.Logger;
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.PostMethod;

public final class Client {
	private static final Logger logger = Logger.getLogger(Client.class
			.getName());

	private Client() {
		// static-only access
	}

	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);
	}

	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:
				logger.warning("Invalid response code (" + post.getStatusCode()
						+ ") from CAS server!");
				logger.info("Response (1k): "
						+ response.substring(0,
								Math.min(1024, response.length())));
				break;
			}
		}

		catch (final IOException e) {
			logger.warning(e.getMessage());
		}

		finally {
			post.releaseConnection();
		}

		return null;
	}

	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();

			switch (post.getStatusCode()) {
			case 201: {
				final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response);

				if (matcher.matches())
					return matcher.group(1);

				logger.warning("Successful ticket granting request, but no ticket found!");
				logger.info("Response (1k): "+ response.substring(0,Math.min(1024, response.length())));
				break;
			}

			default:
				logger.warning("Invalid response code (" + post.getStatusCode()+ ") from CAS server!");
				logger.info("Response (1k): "+ response.substring(0,Math.min(1024, response.length())));
				break;
			}
		}catch (final IOException e) {
			logger.warning(e.getMessage());
		}finally {
			post.releaseConnection();
		}
		return null;
	}

	private static void notNull(final Object object, final String message) {
		if (object == null)
			throw new IllegalArgumentException(message);
	}

	public static void main(final String[] args) {
		final String server = "http://127.0.0.1:8080/cas/v1/tickets";
		final String username = "000000000000000001";
		final String password = "12345678";
		final String service = "http://localhost:8080/service";
		logger.info(getTicketGrantingTicket(server, username, password));//获取TGT票据
		logger.info(getTicket(server, username, password, service));//获取ST票据
	}
}


打开cas-server工程查找ticketExpirationPolicies.xml配置文件,ST票据过期配置,默认时间是10秒钟,使用次数为1 次或者超过10秒没有应用均会引起st过期,手动测试的时候一下ST票据就过期了,更改配置如下:

<bean id="serviceTicketExpirationPolicy"
 class="org.jasig.cas.ticket.support.MultiTimeUseOrTimeoutExpirationPolicy"
          c:numberOfUses="100" c:timeToKill="${st.timeToKillInSeconds:10000}"
           c:timeUnit-ref="SECONDS"/>


如果想了解CAS票据中ST与TGT过期策略,参考资料:http://blog.yoodb.com/yoodb/article/detail/1225  

此时已经拿到了ST票据和TGT票据,一般需要用户信息但是公司要求通过接口的方式提供给其他应用,本人建议CAS3.5.2 Server 集成 OAuth2.0 Server,通过第三方认证接口OAuth2.0 Server特性获取用户信息,具体参考资料:http://blog.yoodb.com/yoodb/article/detail/1226

如果还想了解CAS Server其他插件的使用方法,可以在本站素文宅进行站内搜索或留言。

评论

  1. #1

    Terence(2017/05/29 01:36:04)
    I'd like to cancel a cheque employers view tramadol drug abuse And Samsung did indeed have something that looks radically different, the Galaxy 6 Edge

  2. #2

    Mitchell(2017/05/29 01:03:15)
    I've got a part-time job where can you buy antabuse “People jump at the chance to be the better person we’ve enforced that they are,” Kirschner explains

  3. #3

    Dghonson(2017/05/28 23:10:44)
    I'd like to withdraw $100, please what is trazodone used for in dogs The most important aspect of this stage is to identify the specific goal you are working toward.

  4. #4

    Dylan(2017/05/28 22:38:14)
    Could you tell me the number for ? prazosin hcl 1mg uses The sale, handled by bankers at Credit Suisse and Numis, means a further 4.7m payday for the private equity firm.

  5. #5

    Brant(2017/05/28 21:32:12)
    A First Class stamp indikasi obat elocon The recommendations include improved training and education for NHS staff, as well as local government and service provider employees

  6. #6

    Jenna(2017/05/28 17:15:52)
    I'm not interested in football order linezolid online She was granted "conditional release," meaning she could travel freely throughout East Timor, but could not get her passport back

  7. #7

    Julio(2017/05/28 13:40:48)
    I'm a member of a gym order caduet Both parties are consciously avoiding policy commitments that could prove impossible to maintain in a future negotiation

  8. #8

    Bailey(2017/05/28 13:14:49)
    A few months ranitidine 300 mg price Unlike Earth, the Moon lacks a thick atmosphere and magnetic field to protect it against cosmic radiation

分享:

支付宝

微信