SpringBoot實(shí)例:醫(yī)院統(tǒng)一信息平臺(tái)(oauth2客戶端)

在用戶服務(wù)中睬魂,oauth2認(rèn)證的時(shí)候模庐,客戶端是在代碼中指定的。只有一個(gè)酪惭,這里將它移到數(shù)據(jù)庫中希痴。并提供API可以通過接口維護(hù)客戶端。
之前項(xiàng)目中客戶端這段是這么寫的:

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("client")
            .secret(new BCryptPasswordEncoder().encode("secret"))
            .authorizedGrantTypes("client_credentials", "password", "refresh_token", "authorization_code")
            .scopes("all", "user_info")
            .autoApprove(false) // true: 不會(huì)跳轉(zhuǎn)到授權(quán)頁面
            .redirectUris("http://localhost:8080/login");
    }

下面開始允許多個(gè)客戶端春感,而且客戶端是可配置的砌创。

創(chuàng)建數(shù)據(jù)模型

client.java

@Data
@Entity
@Table(name = "bh_user_client")
public class Client implements Serializable {
    private static final long serialVersionUID = -6421664309310055644L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "client_name")
    private String clientName; // 客戶端名稱
    @Column(name = "client_id")
    private String clientId; // 客戶端ID
    @Column(name = "resource_ids")
    private String resourceIds;
    @Column(name = "client_secret")
    private String clientSecret; // 客戶端密碼
    private String scope; // 客戶端權(quán)限范圍
    @Column(name = "authorized_grant_types")
    private String authorizedGrantTypes; // 客戶端可請(qǐng)求的認(rèn)證類型
    @Column(name = "web_server_redirect_uri", length = 4096)
    private String webServerRedirectUri; // 跳轉(zhuǎn)地址
    private String authorities; // 權(quán)限
    @Column(name = "access_token_validity")
    private Integer accessTokenValidity; // token有效時(shí)間
    @Column(name = "refresh_token_validity")
    private Integer refreshTokenValidity; // 刷新token有效時(shí)間
    @Column(name = "additional_infomation")
    private String additionalInformation; // 補(bǔ)充信息
    private String autoapprove;
    @Column(name = "registered_redirect_uri")
    private String registeredRedirectUri;
    @Column(name = "create_time")
    private Long createTime; // 創(chuàng)建時(shí)間
    private int self = 1; // 是不是自己平臺(tái)的項(xiàng)目
}

ClientRepository.java

public interface ClientRepository extends CustomRepository<Client, Integer>   {

    Client findByClientNameAndIdNot(String name, Integer id);

    Client findByClientIdAndIdNot(String clientId, Integer id);

}

ClientService.java

public interface ClientService {
    /**
     * 添加/修改信息
     * 
     * @param client
     * @return
     * @throws EberException 
     */
    public Client save(Client client) throws BhException;

    /**
     * 根據(jù)id刪除信息
     * 
     * @param id
     * @return
     * @throws EberException 
     */
    public Client delete(Integer id);

    /**
     * 根據(jù)客戶端名稱加載信息
     * 
     * @param name
     * @return
     */
    public Client load(Integer id, String name, String clientId);

    /**
     * 加載所有信息
     * 
     * @return
     */
    public List<Client> list();
    
    /**
     * 當(dāng)前請(qǐng)求的客戶端
     * @return
     * @throws EberException 
     */
    public Client current();
    
    public Set<GrantedAuthority> listClientGrantedAuthorities(String clientId);
}

實(shí)現(xiàn)service

package com.biboheart.huip.user.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;

import com.biboheart.brick.exception.BhException;
import com.biboheart.brick.utils.CheckUtils;
import com.biboheart.brick.utils.TimeUtils;
import com.biboheart.huip.user.domain.Client;
import com.biboheart.huip.user.repository.ClientRepository;
import com.biboheart.huip.user.service.ClientService;

@Service
public class ClientServiceImpl implements ClientService {
    @Autowired
    private ClientRepository clientRepository;

    @Override
    public Client save(Client client) throws BhException {
        if(null == client.getId()) {
            client.setId(0);
        }
        if(CheckUtils.isEmpty(client.getClientName())) {
            throw new BhException("名稱不能為空");
        }
        Client source = clientRepository.findByClientNameAndIdNot(client.getClientName(), client.getId());
        if (null != source && source.getId() != client.getId()) {
            throw new BhException("名稱已存在");
        }
        if(CheckUtils.isEmpty(client.getCreateTime())) {
            client.setCreateTime(TimeUtils.getCurrentTimeInMillis());
        }
        if(null != source) {
            client.setClientId(source.getClientId());
            client.setClientSecret(source.getClientSecret());
        }
        if(CheckUtils.isEmpty(client.getClientId()) || CheckUtils.isEmpty(client.getClientSecret())) {
            client.setClientId(DigestUtils.md5Hex(client.getClientName() + "_client_" + UUID.randomUUID().toString()));
            client.setClientSecret(DigestUtils.md5Hex(client.getClientName() + "_secret_" + UUID.randomUUID().toString()));
        }
        client.setScope("read,write,trust");
        client = clientRepository.save(client);
        return client;
    }

    @Override
    public Client delete(Integer id) {
        Client client = null;
        if (CheckUtils.isEmpty(id)) {
            return null;
        }
        client = clientRepository.findById(id).get();
        if (null == client) {
            return null;
        }
        clientRepository.delete(client);
        return client;
    }

    @Override
    public Client load(Integer id, String name, String clientId) {
        Client client = null;
        if(!CheckUtils.isEmpty(id)) {
            client = clientRepository.findById(id).get();
        }
        if(null == client && !CheckUtils.isEmpty(name)) {
            client = clientRepository.findByClientNameAndIdNot(name, 0);
        }
        if(null == client && !CheckUtils.isEmpty(clientId)) {
            client = clientRepository.findByClientIdAndIdNot(clientId, 0);
        }
        return client;
    }

    @Override
    public List<Client> list() {
        List<Client> clients = clientRepository.findAll();
        return clients;
    }

    @Override
    public Client current() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(null == authentication) {
            return null;
        }
        String clientId = ((OAuth2Authentication) authentication).getOAuth2Request().getClientId();
        if(CheckUtils.isEmpty(clientId)) {
            return null;
        }
        Client client = clientRepository.findByClientIdAndIdNot(clientId, 0);
        return client;
    }
    
    @Override
    public Set<GrantedAuthority> listClientGrantedAuthorities(String clientId) {
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        if(CheckUtils.isEmpty(clientId)) {
            return authorities;
        }
        authorities.add(new SimpleGrantedAuthority("ROLE_CLIENT"));
        return authorities;
    }

}

開放API

ClientController.java

package com.biboheart.huip.user.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.biboheart.brick.exception.BhException;
import com.biboheart.brick.model.BhResponseResult;
import com.biboheart.huip.user.domain.Client;
import com.biboheart.huip.user.service.ClientService;

@RestController
public class ClientController {
    @Autowired
    private ClientService clientService;
    
    /**
     * 保存客戶端
     * @param client
     * @return
     * @throws EberException
     */
    @RequestMapping(value = "/userapi/client/save", method = {RequestMethod.POST})
    public BhResponseResult<?> save(Client client) throws BhException {
        client = clientService.save(client);
        return new BhResponseResult<>(0, "success", client);
    }
    /**
     * 更新客戶端ID
     * @param id
     * @return
     * @throws EberException
     */
    @RequestMapping(value = "/userapi/client/update", method = {RequestMethod.POST, RequestMethod.GET})
    public BhResponseResult<?> update(Integer id) throws BhException {
        Client client = clientService.load(id, null, null);
        if (null == client) {
            throw new BhException("客戶端不存在");
        }
        client.setClientId(null);
        client.setClientSecret(null);
        client = clientService.save(client);
        return new BhResponseResult<>(0, "success", client);
    }
    
    /**
     * 刪除客戶端
     * @param id
     * @return
     */
    @RequestMapping(value = "/userapi/client/delete", method = {RequestMethod.POST, RequestMethod.GET})
    public BhResponseResult<?> delete(Integer id) {
        Client client = clientService.delete(id);
        return new BhResponseResult<>(0, "success", client);
    }
    
    /**
     * 查詢客戶端
     * @param id
     * @param name
     * @param clientId
     * @return
     */
    @RequestMapping(value = "/userapi/client/load", method = {RequestMethod.POST, RequestMethod.GET})
    public BhResponseResult<?> load(Integer id, String name, String clientId) {
        Client client = clientService.load(id, name, clientId);
        return new BhResponseResult<>(0, "success", client);
    }
    
    /**
     * 客戶端列表
     * @return
     */
    @RequestMapping(value = "/userapi/client/list", method = {RequestMethod.POST, RequestMethod.GET})
    public BhResponseResult<?> list() {
        List<Client> clients = clientService.list();
        return new BhResponseResult<>(0, "success", clients);
    }
}

在com.biboheart.huip.user.security包中創(chuàng)建CustomClientDetailsService實(shí)現(xiàn)ClientDetailsService

package com.biboheart.huip.user.security;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;

import com.biboheart.brick.utils.CheckUtils;
import com.biboheart.huip.user.domain.Client;
import com.biboheart.huip.user.service.ClientService;

@Component("customClientDetailsService")
public class CustomClientDetailsService implements ClientDetailsService {
    @Autowired
    private ClientService clientService;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        ClientDetails details;
        Client client = clientService.load(null, null, clientId);
        if(null == client) {
            throw new NoSuchClientException("沒有找到ID為:" + clientId + "的客戶端");
        }
        details = clientToClientDetails(client);
        return details;
    }
    
    private ClientDetails clientToClientDetails(Client client) {
        if(null == client) {
            return null;
        }
        Set<GrantedAuthority> authorities = clientService.listClientGrantedAuthorities(client.getClientId());
        BaseClientDetails details = new BaseClientDetails(client.getClientId(), client.getResourceIds(), client.getScope(),
                client.getAuthorizedGrantTypes(), client.getAuthorities(), client.getRegisteredRedirectUri());
        details.setClientSecret(client.getClientSecret());
        details.setAccessTokenValiditySeconds(client.getAccessTokenValidity());
        details.setRefreshTokenValiditySeconds(client.getRefreshTokenValidity());
        details.setAuthorities(authorities);
        Set<String> autoApproveScopes = new HashSet<>();
        if (!CheckUtils.isEmpty(client.getSelf())) {
            autoApproveScopes.add("true");
        }
        details.setAutoApproveScopes(autoApproveScopes);
        details.setAdditionalInformation(new HashMap<String, Object>());
        return details;
    }

}

修改AuthorizationServerConfiguration

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;
    @Autowired
    @Qualifier("customClientDetailsService")
    private ClientDetailsService clientDetailsService;
    @Autowired
    private UserDetailsService customUserDetailsService;
    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
    }
    
    ...略...
}

這樣就可以根據(jù)數(shù)據(jù)庫中的客戶端進(jìn)行權(quán)限認(rèn)證及授權(quán)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末鲫懒,一起剝皮案震驚了整個(gè)濱河市嫩实,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌窥岩,老刑警劉巖甲献,帶你破解...
    沈念sama閱讀 219,427評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異颂翼,居然都是意外死亡晃洒,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門朦乏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來球及,“玉大人,你說我怎么就攤上這事呻疹⊥奥裕” “怎么了?”我有些...
    開封第一講書人閱讀 165,747評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵诲宇,是天一觀的道長际歼。 經(jīng)常有香客問我,道長姑蓝,這世上最難降的妖魔是什么鹅心? 我笑而不...
    開封第一講書人閱讀 58,939評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮纺荧,結(jié)果婚禮上旭愧,老公的妹妹穿的比我還像新娘。我一直安慰自己宙暇,他們只是感情好输枯,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著占贫,像睡著了一般桃熄。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上型奥,一...
    開封第一講書人閱讀 51,737評(píng)論 1 305
  • 那天瞳收,我揣著相機(jī)與錄音碉京,去河邊找鬼。 笑死螟深,一個(gè)胖子當(dāng)著我的面吹牛谐宙,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播界弧,決...
    沈念sama閱讀 40,448評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼凡蜻,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了垢箕?” 一聲冷哼從身側(cè)響起咽瓷,我...
    開封第一講書人閱讀 39,352評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎舰讹,沒想到半個(gè)月后茅姜,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,834評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡月匣,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評(píng)論 3 338
  • 正文 我和宋清朗相戀三年钻洒,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片锄开。...
    茶點(diǎn)故事閱讀 40,133評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡素标,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出萍悴,到底是詐尸還是另有隱情头遭,我是刑警寧澤,帶...
    沈念sama閱讀 35,815評(píng)論 5 346
  • 正文 年R本政府宣布癣诱,位于F島的核電站计维,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏撕予。R本人自食惡果不足惜鲫惶,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望实抡。 院中可真熱鬧欠母,春花似錦、人聲如沸吆寨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽挺勿。三九已至,卻和暖如春耐量,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背缩擂。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留添寺,地道東北人胯盯。 一個(gè)月前我還...
    沈念sama閱讀 48,398評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像计露,于是被迫代替她去往敵國和親博脑。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容