CasRestV1Endpoint.java 12.0 KB
Newer Older
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 

/**
 * 
 */
package org.maxkey.authz.cas.endpoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
26
import org.maxkey.authn.LoginCredential;
M
MaxKey 已提交
27
import org.maxkey.authn.provider.AbstractAuthenticationProvider;
M
MaxKey 已提交
28
import org.maxkey.authn.web.AuthorizationUtils;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
29
import org.maxkey.authz.cas.endpoint.response.ServiceResponseBuilder;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
30 31 32
import org.maxkey.authz.cas.endpoint.ticket.CasConstants;
import org.maxkey.authz.cas.endpoint.ticket.ServiceTicketImpl;
import org.maxkey.authz.cas.endpoint.ticket.TicketGrantingTicketImpl;
M
MaxKey 已提交
33 34
import org.maxkey.entity.UserInfo;
import org.maxkey.entity.apps.AppsCasDetails;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
35
import org.maxkey.util.StringUtils;
M
MaxKey 已提交
36
import org.maxkey.web.HttpResponseConstants;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
37 38 39 40 41 42 43 44 45
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
46
import org.springframework.security.core.Authentication;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
47 48 49 50 51 52 53
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

M
v 3.2.0  
MaxKey 已提交
54 55
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
56

MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
57 58 59 60
/**
 * @author Crystal.Sea
 * https://apereo.github.io/cas/6.2.x/protocol/REST-Protocol.html
 */
M
v 3.2.0  
MaxKey 已提交
61
@Tag(name = "2-4-CAS REST API文档模块")
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
62 63
@Controller
public class CasRestV1Endpoint  extends CasBaseAuthorizeEndpoint{
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
64
    final static Logger _logger = LoggerFactory.getLogger(CasRestV1Endpoint.class);
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
65 66
	
    @Autowired
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
67
    @Qualifier("authenticationProvider")
68
    AbstractAuthenticationProvider authenticationProvider ;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
69
    
M
v 3.2.0  
MaxKey 已提交
70
    @Operation(summary = "CAS REST认证接口", description = "通过用户名密码获取TGT",method="POST")
M
MaxKey 已提交
71
	@RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1, 
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
72 73 74 75 76 77 78 79 80
	        method=RequestMethod.POST, 
	        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<String> casLoginRestTickets(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value=CasConstants.PARAMETER.SERVICE,required=false) String casService,
            @RequestParam(value=CasConstants.PARAMETER.REST_USERNAME,required=true) String username,
            @RequestParam(value=CasConstants.PARAMETER.REST_PASSWORD,required=true) String password){
	    try {
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
81
    	    if (StringUtils.isBlank(password)) {
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
82 83 84
                throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request");
            }
    	    
85 86 87 88 89 90 91
    	    LoginCredential loginCredential =new LoginCredential(username,password,"normal");
    	    
    	    Authentication  authentication  = authenticationProvider.authenticate(loginCredential);
    	    if(authentication == null) {
	    	    _logger.debug("Bad Credentials Exception");
	            return new ResponseEntity<>("Bad Credentials", HttpStatus.BAD_REQUEST);
    	    }
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
92
    	    
M
MaxKey 已提交
93
            TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",AuthorizationUtils.getAuthentication(),null);
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
94
            
95
            String ticket=casTicketGrantingTicketServices.createTicket(ticketGrantingTicket);
M
MaxKey 已提交
96
            String location = applicationConfig.getServerPrefix()+CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1 +"/" + ticket;
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
97 98
            HttpHeaders headers = new HttpHeaders();
            headers.add("location", location);
M
MaxKey 已提交
99 100
            _logger.trace("ticket {}" , ticket);
            _logger.trace("location {}" , location);
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
101 102
            return new ResponseEntity<>("Location: " + location, headers ,HttpStatus.CREATED);
 
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
103 104 105 106 107 108 109 110 111 112
	    } catch (final AuthenticationException e) {
	        _logger.error("BadCredentialsException ", e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (final Exception e) {
            
            _logger.error("Exception ", e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
	}
	
M
v 3.2.0  
MaxKey 已提交
113
    @Operation(summary = "CAS REST认证接口", description = "通过TGT获取ST",method="POST")
M
MaxKey 已提交
114
	@RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1+"/{ticketGrantingTicket}", 
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
115 116
	            method=RequestMethod.POST, 
	            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
117
    public ResponseEntity<String> requestServiceTicket(
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
118 119 120 121 122 123 124 125 126
	            HttpServletRequest request,
	            HttpServletResponse response,
	            @PathVariable("ticketGrantingTicket") String ticketGrantingTicket,
	            @RequestParam(value=CasConstants.PARAMETER.SERVICE,required=false) String casService,
	            @RequestParam(value=CasConstants.PARAMETER.RENEW,required=false) String renew,
	            @RequestParam(value=CasConstants.PARAMETER.REST_USERNAME,required=false) String username,
	            @RequestParam(value=CasConstants.PARAMETER.REST_PASSWORD,required=false) String password){
	       try {
            TicketGrantingTicketImpl ticketGrantingTicketImpl = 
127
                    (TicketGrantingTicketImpl) casTicketGrantingTicketServices.get(ticketGrantingTicket);
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
128
            
M
MaxKey 已提交
129
            AppsCasDetails  casDetails=casDetailsService.getAppDetails(casService , true);
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
130 131
            
            ServiceTicketImpl serviceTicket=new ServiceTicketImpl(ticketGrantingTicketImpl.getAuthentication(),casDetails);
M
MaxKey 已提交
132
            String ticket = ticketServices.createTicket(serviceTicket);
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
133 134 135 136 137 138 139
            return new ResponseEntity<>(ticket, HttpStatus.OK);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
	       return new ResponseEntity<>("", HttpStatus.BAD_REQUEST);
	   }
M
v 3.2.0  
MaxKey 已提交
140
    @Operation(summary = "CAS REST认证接口", description = "检查TGT状态",method="GET")
M
MaxKey 已提交
141
    @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1 + "/{ticketGrantingTicket}", 
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
142 143 144 145 146 147 148
	            method=RequestMethod.GET)
    public ResponseEntity<String> verifyTicketGrantingTicketStatus(
	            @PathVariable("ticketGrantingTicket") String ticketGrantingTicket,
	            HttpServletRequest request,
	            HttpServletResponse response){
	       try {
            TicketGrantingTicketImpl ticketGrantingTicketImpl = 
149
                       (TicketGrantingTicketImpl) casTicketGrantingTicketServices.get(ticketGrantingTicket);
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
150 151 152 153 154 155 156 157 158
                if(ticketGrantingTicketImpl != null) {
                    return new ResponseEntity<>("", HttpStatus.OK);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
	       return new ResponseEntity<>("", HttpStatus.NOT_FOUND);
	}
    
M
v 3.2.0  
MaxKey 已提交
159
    @Operation(summary = "CAS REST认证接口", description = "注销TGT状态",method="DELETE")
M
MaxKey 已提交
160
    @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1+"/{ticketGrantingTicket}", 
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
161 162 163 164 165 166 167
            method=RequestMethod.DELETE)
    public ResponseEntity<String> destroyTicketGrantingTicket(
            @PathVariable("ticketGrantingTicket") String ticketGrantingTicket,
            HttpServletRequest request,
            HttpServletResponse response){
       try {
        TicketGrantingTicketImpl ticketGrantingTicketImpl = 
168
                   (TicketGrantingTicketImpl) casTicketGrantingTicketServices.remove(ticketGrantingTicket);
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
169 170 171 172 173 174 175 176 177
            if(ticketGrantingTicketImpl != null) {
                return new ResponseEntity<>("", HttpStatus.OK);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
       return new ResponseEntity<>("", HttpStatus.NOT_FOUND);
    }
	   
M
v 3.2.0  
MaxKey 已提交
178
    @Operation(summary = "CAS REST认证接口", description = "用户名密码登录接口",method="POST")   
M
MaxKey 已提交
179
	@RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_USERS_V1, 
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
180 181 182 183 184 185 186 187
            method=RequestMethod.POST, 
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<String> casLoginRestUsers(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value=CasConstants.PARAMETER.SERVICE,required=false) String casService,
            @RequestParam(value=CasConstants.PARAMETER.REST_USERNAME,required=true) String username,
            @RequestParam(value=CasConstants.PARAMETER.REST_PASSWORD,required=true) String password){
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
188 189 190 191 192
	    try {
            if (password == null || password.isEmpty()) {
                throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request");
            }
            
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
193
            LoginCredential loginCredential =new LoginCredential(username,password,"CASREST");
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
194
            
M
MaxKey 已提交
195
            authenticationProvider.authenticate(loginCredential,false);
M
MaxKey 已提交
196 197
            UserInfo userInfo = AuthorizationUtils.getUserInfo();
            TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",AuthorizationUtils.getAuthentication(),null);
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
198
            
199
            String ticket=casTicketGrantingTicketServices.createTicket(ticketGrantingTicket);
M
MaxKey 已提交
200
            String location = applicationConfig.getServerPrefix() + CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1 + ticket;
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
201 202 203
            HttpHeaders headers = new HttpHeaders();
            headers.add("location", location);
            ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder();
M
MaxKey 已提交
204
            serviceResponseBuilder.setFormat(HttpResponseConstants.FORMAT_TYPE.JSON);
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
205
            //for user
M
MaxKey 已提交
206
            serviceResponseBuilder.setAttribute("userId", userInfo.getId());
MaxKey单点登录官方's avatar
CAS FIX  
MaxKey单点登录官方 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
            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);
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
225 226 227 228 229 230 231 232
        } catch (final AuthenticationException e) {
            _logger.error("BadCredentialsException ", e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (final Exception e) {
            
            _logger.error("Exception ", e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
233 234 235
    }
	
}