springboot 통합 CAS 단일 로그 인 을 위 한 예제 코드
19985 단어 springbootCAS단일 로그 인
단일 로그 인
의미:서로 신뢰 하 는 여러 시스템 에서 한 시스템 에 로그 인하 면 다른 시스템 에 접근 할 수 있 습 니 다.
CAS 는 광범 위 한 단일 로그 인 을 사용 하여 이 루어 집 니 다.클 라 이언 트 CAS Client 와 서버 CAS Service 로 나 뉘 는데 클 라 이언 트 는 우리 의 시스템 입 니 다.서버 는 인증 센터 이 고 CAS 에서 제공 합 니 다.우 리 는 조금 만 수정 하고 시작 하면 사용 할 수 있 습 니 다.~~
효과 시범
https 인증서
CAS Service 는 https 방식 을 사용 해 야 합 니 다.인증서 가 필요 합 니 다.살 수도 있 고 스스로 만 들 수도 있 습 니 다.
사실 이 단 계 는 생략 할 수 있 습 니 다.방문 할 때 http 를 사용 하면 됩 니 다.다만 카 스 가 경 고 를 할 뿐 입 니 다.
절 차 는 코끼리 를 냉장고 에 넣 는 것 처럼 간단 하 다.총 3 단계:
keytool -genkey -alias cainiao -keyalg RSA -keystore E:sslcainiao.keystore
매개 변수 설명:
실행 중 에 많은 질문 을 할 것 입 니 다.당신 의 이름과 성 은 무엇 입 니까?
이 때 도 메 인 이름 을 입력 해 야 합 니 다.다음 방문 주소 로 서 다른 것 은 마음대로 해 야 합 니 다.
실행 후 키 파일 생 성 cainiao.keystore
2.인증서 생 성
keytool -export -alias cainiao -storepass 123456 -file E:/ssl/cainiao.cer -keystore E:/ssl/cainiao.keystore
매개 변수 설명:
-storepass 키 파일 생 성 시 설정 한 비밀번호
-file 에서 인증 서 를 내 보 낼 파일 이름 을 cainiao.cer 로 지정 합 니 다.
-키스 토어 에서 이전에 생 성 된 키 파일 의 파일 이름 지정
실행 후 디 렉 터 리 에 cainiao.cer 인증서 가 생 성 됩 니 다.
3.인증서 가 져 오기
keytool -import -alias cainiao -keystore C:/"Program Files"/Java/jdk1.8.0_181/jre/lib/security/cacerts -file E:/ssl/cainiao.cer -trustcacerts
인증 서 를 JDK 신뢰 라 이브 러 리 로 가 져 오기
원래 의$JAVAHOME/jre/lib/security/cacerts 파일 은 먼저 삭제 해 야 합 니 다.그렇지 않 으 면
Keystore was tampered with, or password was incorrect
을 보고 합 니 다.다음은 전체 과정 입 니 다.
PS E:\ssl> keytool -genkey -alias cainiao -keyalg RSA -keystore E:\ssl\cainiao.keystore
:
:
?
[Unknown]: www.cainiao.com
?
[Unknown]: cainian
?
[Unknown]: cainiao
?
[Unknown]: wx
/ / ?
[Unknown]: js
/ ?
[Unknown]: CN
CN=www.cainiao.com, OU=cainian, O=cainiao, L=wx, ST=js, C=CN ?
[ ]: y
<cainiao>
( , ):
:
------------------------------------------------------------------------------------
PS E:\ssl> keytool -export -alias cainiao -storepass 123456 -file E:/ssl/cainiao.cer -keystore E:/ssl/cainiao.keystore
<E:/ssl/cainiao.cer>
------------------------------------------------------------------------------------
PS E:\ssl> keytool -import -alias cainiao -keystore C:/"Program Files"/Java/jdk1.8.0_181/jre/lib/security/cacerts -file E:/ssl/cainiao.cer -trustcacerts
:
: CN=www.cainiao.com, OU=cainian, O=cainiao, L=wx, ST=js, C=CN
: CN=www.cainiao.com, OU=cainian, O=cainiao, L=wx, ST=js, C=CN
: 509d1aea
Wed Jun 17 22:02:55 CST 2020 Tue Sep 15 22:02:55 CST 2020
:
MD5: 5B:B2:7C:D7:B7:31:C5:7C:1C:BC:F7:DA:A8:2D:1C:B2
SHA1: F6:76:55:55:D7:48:E3:9F:3A:B6:EE:68:1F:BE:DC:DE:51:B1:33:E5
SHA256: 24:53:18:CD:E8:95:65:D8:6E:6A:7B:8E:79:CB:91:BD:F4:2E:C3:99:59:D1:76:12:A8:95:45:2A:4B:03:E4:AD
: SHA256withRSA
: 2048 RSA
: 3
:
#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 70 B3 D5 76 36 EA 54 BA 75 C1 A1 5C DA 76 82 0E p..v6.T.u..\.v..
0010: 4D F4 C9 05 M...
]
]
? [ ]: y
마지막 으로 hosts 설정 127.0.0.1 www.cainiao.com
CAS 서비스 구축github 에서 템 플 릿 https://github.com/apereo/cas-overlay-template 을 끌 어 올 려 야 합 니 다.
5.3 이후 에는 모두 gradle 프로젝트 였 고 5.3 이전 에는 maven 프로젝트 였 으 며 5.3 버 전 을 다운 받 았 습 니 다.
1.pom 안의
2.>루트 디 렉 터 리 에/src/main/resources 디 렉 터 리 만 들 기
3.>생 성 된 키 파일 을/src/main/resources 디 렉 터 리 에 복사 합 니 다.
4.>overlays/org.ape레오.cas.cas-server-webapp-tomcat-5.3.14/WEB-INF/classes/application.properties 파일 을 두 번 째 로 만 든 디 렉 터 리 에 복사 합 니 다.
5.복사 한/src/main/resources/application.properties 파일 을 수정 하고 위의 인증서 정보 에 따라 사실대로 작성 합 니 다.
server.ssl.key-store=classpath:cainiao.keystore
server.ssl.key-store-password=123456
server.ssl.key-password=123456
6.>my sql 데이터 베 이 스 를 연결 하여 pom 에 의존 도 를 추가 합 니 다.
<dependency>
<groupId>org.apereo.cas</groupId>
<artifactId>cas-server-support-jdbc</artifactId>
<version>${cas.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
xmlsectool-2.0.0.jar 가방 이 내 려 오지 않 는 것 을 발견 할 수 있 습 니 다.이것 은 아 리 클 라 우 드 의 창고 입 니 다.Maven 중앙 창고 에 다운로드 한 후에 로 컬 창고 에 설치 해 야 합 니 다.로 컬 창고 에 직접 설치 하 는 것 이 아니 라 jar 가방 은 모두 명령 을 사용 하여 로 컬 창고 에 설치 해 야 합 니 다.화면 음악 설치:install-file-dfile="E:다운로드 xmlsectool-2.0.0.jar""-DgroupId=net.shibboleth.tool""-DirtifactId=xmlsectool""-Dversion=2.0.0""-Dpackaging=jar"
jar 패키지 설치 로 컬 창고 노트
7.>복 사 된/src/main/resources/application.properties 파일 에 다음 과 같은 정 보 를 추가 합 니 다.
# sql,
cas.authn.jdbc.query[0].sql=select * from sys_user where username=?
# sql ( )
cas.authn.jdbc.query[0].fieldPassword=password
# ,1 ,
cas.authn.jdbc.query[0].fieldExpired=expired
# ,1 ,
cas.authn.jdbc.query[0].fieldDisabled=disabled
# hibernate
cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect
#
cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver
#
cas.authn.jdbc.query[0].url=jdbc:mysql://localhost:3306/cas?useUnicode=true&characterEncoding=UTF-8
#
cas.authn.jdbc.query[0].user=root
#
cas.authn.jdbc.query[0].password=123456
# , encodingAlgorithm , NONE
cas.authn.jdbc.query[0].passwordEncoder.type=DEFAULT
cas.authn.jdbc.query[0].passwordEncoder.characterEncoding=UTF-8
cas.authn.jdbc.query[0].passwordEncoder.encodingAlgorithm=MD5
데이터베이스 sql,사용자 정보 표 첨부
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`expired` int(11) DEFAULT NULL,
`disabled` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ('1', 'admin', '21232f297a57a5a743894a0e4a801fc3', '0', '1');
INSERT INTO `sys_user` VALUES ('2', 'cainiao', '6b757206058785025cd90c8d865c8e43', '1', '0');
INSERT INTO `sys_user` VALUES ('3', 'mashu', 'd1f21ceb3f710ebbd9f408274aee1193', '0', '0');
사용자 이름과 비밀 번 호 는 데이터베이스 에서 MD5 로 암호 화 되 어 있 습 니 다.이렇게 하면 CAS service 구축 이 완료 되 고 루트 디 렉 터 리 에서
build.cmd run
명령 으로 시작 합 니 다.READY 의 branner 가 나타 나 면 접근 주소 가 시 작 됩 니 다.https://www.cainiao.com:8443/cas/login
mashu 가 정상적으로 로그 인 했 습 니 다.cainiao 는 비밀 번 호 를 수정 해 야 합 니 다.admin 은 비활성화 되 어 예상 에 부합 합 니 다.
CAS 클 라 이언 트 구축
spring boot 프로젝트 를 만 듭 니 다.
1.케이스 클 라 이언 트 의 의존 도 를 추가 하여 현재 최신 2.3.0-GA 버 전 을 선택 하 겠 습 니 다.
<dependency>
<groupId>net.unicon.cas</groupId>
<artifactId>cas-client-autoconfig-support</artifactId>
<version>2.3.0-GA</version>
</dependency>
2.시동 류 에 주석 @EnableCasClient
추가3.application.properties 에 설정 추가
#cas
cas.server-url-prefix=https://www.cainiao.com:8443/cas
#cas
cas.server-login-url=https://www.cainiao.com:8443/cas/login
#
cas.client-host-url=http://www.mashu.com:8080
cas.validation-type=CAS3
4.hosts 설정 을 추가 하고 클 라 이언 트 의 방문 주 소 를 hosts 에 설정 합 니 다.
127.0.0.1 www.mashu.com
이렇게 하면 클 라 이언 트 가 설정 되 어 있 습 니 다.단일 로그 인
컨트롤 러 를 써 서 방문 해 보 겠 습 니 다.
@RestController
public class TestController {
@RequestMapping("/hello")
public String hello() {
return "word";
}
}
방문 하 다.http://www.mashu.com:8080/hello인증 되 지 않 은 서비스
기 쁜 마음으로 잘못 을 보고 하 다.
서버 에서 클 라 이언 트 의 http 프로 토 콜 요청 을 허용 하지 않 기 때 문 입 니 다.서버 에 대해 다음 과 같은 수정 을 해서 그 가 타협 하도록 해 야 한다.
1.>overlays/org.ape레오.cas.cas-server-webapp-tomcat-5.3.14/WEB-INF/classes/services/HTTPSandIMAPS-10000001.json 파일 수정
"serviceId" "^(https|imaps)://.*" "^(https|imaps|http)://.*"
2.>application.properties 파일 에 추가:
# http
cas.tgc.secure=false
cas.serviceRegistry.initFromJson=true
재 방문http://www.mashu.com:8080/hello서버 에 주소 가 있 는 로그 인 페이지 를 볼 수 있 습 니 다.계 정 비밀 번 호 를 입력 mashu/mashu,로그 인 성공 후 다시 돌 아 왔 습 니 다!하하하하 트림,그리고 등록 증 을 지 참 했 습 니 다.
다 중 시스템 로그 인
클 라 이언 트 를 다시 시작 하고 아이디어 의 edit configurations 설정 을 엽 니 다.선택 Allow parallel run
application.properties,서비스의 포트 등 정 보 를 수정 하고 시작 을 클릭 하면 동시에 시작 할 수 있 습 니 다(8081/8080)두 클 라 이언 트 를 시작 할 수 있 습 니 다.
server.port=8081
#cas
cas.server-url-prefix=https://www.cainiao.com:8443/cas
#cas
cas.server-login-url=https://www.cainiao.com:8443/cas/login
#
cas.client-host-url=http://www.mshu.com:8081
cas.validation-type=CAS3
두 번 째 클 라 이언 트 방문http://www.mshu.com:8081/hello,(host 를 먼저 설정 해 야 합 니 다)바로 로그 인 했 습 니 다.단일 로그 인 을 완 료 했 습 니 다.주문 하여 게재 하 다
두 개의 프로필 추가 하기;
1. CasProperties.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import javax.validation.constraints.NotNull;
@ConfigurationProperties(prefix = "cas",ignoreUnknownFields = true)
public class CasProperties {
/**
* CAS server URL E.g. https://example.com/cas or https://cas.example. Required.
* CAS url
*/
@NotNull
private String serverUrlPrefix;
/**
* CAS server login URL E.g. https://example.com/cas/login or https://cas.example/login. Required.
* CAS /login
*/
@NotNull
private String serverLoginUrl;
/**
* CAS-protected client application host URL E.g. https://myclient.example.com Required.
*
*/
@NotNull
private String clientHostUrl;
/**
* ,
*/
private String ignorePattern;
/**
* UrlPatternMatcherStrategy
*/
private String ignoreUrlPatternType;
public String getServerUrlPrefix() {
return serverUrlPrefix;
}
public void setServerUrlPrefix(String serverUrlPrefix) {
this.serverUrlPrefix = serverUrlPrefix;
}
public String getServerLoginUrl() {
return serverLoginUrl;
}
public void setServerLoginUrl(String serverLoginUrl) {
this.serverLoginUrl = serverLoginUrl;
}
public String getClientHostUrl() {
return clientHostUrl;
}
public void setClientHostUrl(String clientHostUrl) {
this.clientHostUrl = clientHostUrl;
}
public String getIgnorePattern() {
return ignorePattern;
}
public void setIgnorePattern(String ignorePattern) {
this.ignorePattern = ignorePattern;
}
public String getIgnoreUrlPatternType() {
return ignoreUrlPatternType;
}
public void setIgnoreUrlPatternType(String ignoreUrlPatternType) {
this.ignoreUrlPatternType = ignoreUrlPatternType;
}
}
2. Configs.java
import org.jasig.cas.client.authentication.AuthenticationFilter;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.session.SingleSignOutHttpSessionListener;
import org.jasig.cas.client.util.HttpServletRequestWrapperFilter;
import org.jasig.cas.client.validation.Cas30ProxyReceivingTicketValidationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableConfigurationProperties(CasProperties.class)
public class Configs {
@Autowired
private CasProperties configProps;
/**
*
* @return
*/
@Bean
public FilterRegistrationBean filterSingleRegistration() {
final FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new SingleSignOutFilter());
//
registration.addUrlPatterns("/*");
Map<String,String> initParameters = new HashMap<String, String>();
initParameters.put("casServerUrlPrefix", configProps.getServerUrlPrefix());
registration.setInitParameters(initParameters);
//
registration.setOrder(1);
return registration;
}
/**
* Cas30ProxyReceivingTicketValidationFilter
* @return
*/
@Bean
public FilterRegistrationBean filterValidationRegistration() {
final FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new Cas30ProxyReceivingTicketValidationFilter());
//
registration.addUrlPatterns("/*");
Map<String,String> initParameters = new HashMap<String, String>();
initParameters.put("casServerUrlPrefix", configProps.getServerUrlPrefix());
initParameters.put("serverName", configProps.getClientHostUrl());
initParameters.put("useSession", "true");
registration.setInitParameters(initParameters);
//
registration.setOrder(2);
return registration;
}
/**
*
* @return
*/
@Bean
public FilterRegistrationBean filterAuthenticationRegistration() {
final FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new AuthenticationFilter());
//
registration.addUrlPatterns("/*");
Map<String,String> initParameters = new HashMap<String, String>();
initParameters.put("casServerLoginUrl", configProps.getServerLoginUrl());
initParameters.put("serverName", configProps.getClientHostUrl());
if(configProps.getIgnorePattern() != null && !"".equals(configProps.getIgnorePattern())){
initParameters.put("ignorePattern", configProps.getIgnorePattern());
}
// UrlPatternMatcherStrategy
if(configProps.getIgnoreUrlPatternType() != null && !"".equals(configProps.getIgnoreUrlPatternType())){
initParameters.put("ignoreUrlPatternType", configProps.getIgnoreUrlPatternType());
}
registration.setInitParameters(initParameters);
//
registration.setOrder(3);
return registration;
}
/**
* request wraper
* @return
*/
@Bean
public FilterRegistrationBean filterWrapperRegistration() {
final FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new HttpServletRequestWrapperFilter());
//
registration.addUrlPatterns("/*");
//
registration.setOrder(4);
return registration;
}
/**
*
* @return
*/
@Bean
public ServletListenerRegistrationBean<EventListener> singleSignOutListenerRegistration(){
ServletListenerRegistrationBean<EventListener> registrationBean = new ServletListenerRegistrationBean<EventListener>();
registrationBean.setListener(new SingleSignOutHttpSessionListener());
registrationBean.setOrder(1);
return registrationBean;
}
}
로그 인 주소:https://www.cainiao.com:8443/cas/logout서버 에서 종료 합 니 다.클 라 이언 트 를 다시 방문 하면 자동 으로 로그 인 페이지 로 넘 어 갑 니 다.즉,클 라 이언 트 도 자동 으로 종료 되 었 습 니 다.
몇몇 문제
처음에 클 라 이언 트 에 도 인증 서 를 추가 하고 https 로 접근 하고 싶 었 습 니 다.서버 에서 http 를 지원 하지 않도록 수정 합 니 다.
인증 서 를 추가 한 후에 단일 로그 인 이 정상 이지 만 로그 인 기능 이 항상 실 패 했 습 니 다.서버 가 종료 되 었 고 클 라 이언 트 가 종료 되 지 않 았 습 니 다.
나 는 클 라 이언 트 설정 의 로그 인 에 문제 가 있다 고 생각 했 는데 반나절 을 했 지만 성공 하지 못 했다.나중에 나 는 클 라 이언 트 의 인증 서 를 제거 하고 성공 했다.생각해 보 니 우리 가 만 든 인증 서 는 서버 에서 인 정 받 지 못 하기 때 문 일 것 입 니 다.로그 인 할 때 서버 에서 클 라 이언 트 에 게 방송 을 해 야 하기 때 문 입 니 다.우리 가 이전에 수정 한
HTTPSandIMAPS-10000001.json
파일 은 클 라 이언 트 가 서버 에 요청 하 는 데 만 작용 하기 때 문 입 니 다.게재 와 상반되다.springboot 설정 인증 서 를 사용 할 때 2.1.0.RELEASE 이상 버 전의 spring-boot-starter-parent 는 안 됩 니 다.잘못 을 보고 할 수 있다.
springboot 통합 CAS 단일 로그 인 을 실현 하 는 예제 코드 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 springboot 통합 CAS 단일 로그 인 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin Springboot -- 파트 14 사용 사례 REST로 전환하여 POST로 JSON으로 전환前回 前回 前回 記事 の は は で で で で で で を 使っ 使っ 使っ て て て て て リクエスト を を 受け取り 、 reqeustbody で 、 その リクエスト の ボディ ボディ を を 受け取り 、 関数 内部 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.